Secure a Node API with OAuth 2.0 Client Credentials

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
Securing server-to-server API services can be tricky. OAuth 2.0 is an excellent way to offload user authentication to another service, but what if there is no user to authenticate? In this article, I’ll show you how you can use OAuth 2.0 outside the context of a user, in what is also known as the Client Credentials Flow.
Instead of storing and managing API keys for your clients (other servers), you can use a third-party service to manage authorization for you. The way this works is that an API client sends a request to an OAuth server asking for an API token. That token is then sent from the API client to your API service along with their request. Once you have the client’s token, you can verify its validity without needing to store any information about the client.

How the Client Credentials Flow Verification Works
One way to verify tokens you receive to your API service is to forward the token to the OAuth server to ask if it is valid. The downside to this method is each API request sent to your server requires a request sent to the OAuth server as well, which increases the time it takes for you to respond to your client. An alternative is to use something called local validation, a strategy popularized by JSON Web Tokens (JWT). A JWT contains your claims (client data) in unencrypted, machine-readable JSON.
When using the local validation pattern to validate an API token (JWT), you can use math to validate that:
The token your API is receiving hasn’t been tampered with The token your API is receiving hasn’t expired That certain pieces of JSON data encoded in the token are what you expect them to be
How is that secure? you might be wondering. JWTs contain three parts: a header, a payload, and a signature. The header and payload are simple base64 encoded strings, which can easily be decrypted and read. The signature uses an algorithm listed in the header, along with a private key, to create a hash of the header and payload. The hash can’t be recreated without the private key, but it can be verified with a public key.
In a way, this is like a driver’s license or a passport. It’s quite difficult to forge, but it’s very easy for somebody to look at it and see your name, date of birth, and other information. You can scan the barcode, test it with a black light, or look for watermarks to help verify its validity.
While similar in concept, a valid JWT would actually be far more difficult to forge. Someone with enough skill can create a convincing driver’s license, but without the private key it could take a modern computer years to brute force a valid JWT signature. Tokens should also have an expiration. While configurable, a solid default is one hour. This means a client would need to request a new token every 60 minutes if it needs to make a new request to your API server. This is an extra layer of security in case your token is compromised. Who knows? Maybe there’s a quantum computer out there that can recreate the signature within a couple hours.
Now that you understand the basics of the OAuth 2.0 client credentials flow works, let’s build a Node API that uses Client Credentials and Okta.
What is Okta?
In short, we make identity management easier, more secure, and more scalable than what you’re used to. Okta is an API service that allows you to create, edit, and securely store user accounts and user account data, and connect them with one or more applications. Our API enables you to:

Authenticate and authorize your users
Store data about your users
Perform password-based and social login
Secure your application with multi-factor authentication
And much more! Check out our product documentation for more information

Register for a forever-free developer account, and when you’re done, come back to learn more about building secure APIs in Node!
Create a Basic Node API
In order to get started, I’ll show you how to create a basic API in Node. Node keeps a list of dependencies along with other metadata in a file called package.json.
Assuming you have Node installed already, create a new folder for your API server. You can then use npm to generate a package.json for you. The command npm init will prompt you for some information, but you can just keep hitting Enter to stick to the defaults.
$ mkdir client-credentials-flow
$ cd client-credentials-flow
$ git init
$ npm init

The quickest way to get an API server up and running in Node is by using Express. You can add Express as a dependency with the command npm install express@4.16.3 –save. This creates a folder called node_modules where express and anything it depends on are downloaded, and your app can then use those. To make development go faster, you can also add a dev dependency called nodemon, which will restart your server whenever you make code changes. To add a dev-dependency, use the -D flag: npm install -D nodemon@1.17.5.
When building Node apps, you usually want to ignore storing the node_modules folder in your git repo. You can do that by adding node_modules to your .gitignore file.
echo node_modules >> .gitignore

Package managers will also include a file (e.g. package-lock.json or yarn.lock) so that when you download the node_modules on another machine (with npm install or yarn), the same version gets downloaded. This helps prevent any inconsistencies between servers, and keeps you from wondering why something works on your machine, but not in production. Make sure to commit that file to your git repo as well:
$ git add .
$ git commit -m “Adding package files."

You can also add scripts to your package.json folder to run these commands. Create a start script with the command node . (the . tells it to run the script listed in your package.json as main, which by default is index.js. You’ll also want to create a dev script with the command nodemon *.js node .. Command line dependencies, like nodemon, are in the path when running inside a node script. You can now run these commands with npm start or npm run dev. Your package.json file should now look something like this:
package.json
{
"name": "client-credentials-flow",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon *.js node .",
"start": "node .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.3"
},
"devDependencies": {
"nodemon": "^1.17.5"
}
}

Now for the most basic “Hello World” express app:
index.js
const express = require(‘express’)
const app = express()

app.get(‘/’, (req, res) => res.send(‘Hello World!’))

const port = process.env.PORT || 3000
app.listen(port, () => console.log(`Listening on port ${port}`))

That’s it! To start it, type npm run dev in a terminal window. You can leave this running while we make changes, and it will automatically restart to reflect new changes. Now go to http://localhost:3000 in your browser (or on the command line with curl http://localhost:3000) and you should see Hello World! echoed back.
Register with an OAuth 2.0 Provider for Your Node API
Now to secure the app. This is where you need to set up an OAuth 2.0 service. Okta is a cloud-based service that allows developers to easily and securely store OAuth 2.0 tokens, user accounts, and user data, then connect them with one or multiple applications. Okta also provides libraries for many languages, including Node, to make their API very easy for a developer to integrate into a huge variety of apps.
You can use Okta to quickly and easily set up server-to-server authentication. If you don’t already have an account, sign up for a free Okta Developer account. Once you register, you’ll be given a unique Okta Org URL (e.g. https://{yourOktaDomain}) and an email to activate your new account.
You’ll need two parts in order to make client-to-server authentication work: an authorization server, and a test client/application.
Create an Authorization Server
The authorization server is where clients can request a token to use on your API server. Inside the Okta dashboard, click on the API tab in the header, then select the Authorization Servers tab. Click Add Authorization Server, then give your server a useful name and description. The Audience should be an absolute path for the server that will be consuming the tokens.

Once you create the authorization server, you will need a scope for your clients to access. Click the Scopes tab and add a scope. You can have many of these, which can help define what parts of the API are being used, or even who is using it.

Now that you have a scope, you also need to specify some rules to say who has access to it. Click the Access Policies tab and create a new policy. For now, just allow access to All clients. Then click Add Rule and give it a name. Since this is only for client credentials, remove the other grant types for acting on behalf of a user (Authorization Code, Implicit, and Resource Owner Password) so the only grant type is Client Credentials. Aside from that, just use the default settings for now.

Back on the Settings tab, take note of the Issuer. This is the address clients will use to request a token, and what your API server will use to verify that those tokens are valid.
Create a Test Client
In your Okta dashboard, click on Applications in the top header. Applications are also known as clients, so this is where you can create a test client. Click Add Application and choose Service (Machine-to-Machine). The only information it needs is a name, so you can use something like Test Client. This will give you the credentials for your client (in this testing case, that would be you).

Secure your Node API
You now have all the pieces of the puzzle to make it so only authenticated users get the beloved “Hello World” welcome message, and everybody else gets an error.
Safely Store Your Credentials
You’ll want to store your credentials safely. One way of doing this is to keep a file locally that isn’t stored in git (especially useful if your code is open source, but still a good thing to do regardless). This also lets you use the same code for multiple applications (e.g. dev and production environments).
The post Secure a Node API with OAuth 2.0 Client Credentials appeared first on SitePoint.

Link: https://developer.okta.com/blog/2018/06/06/node-api-oauth-client-credentials

How Upload Files With Node.js

Front-end development throws a lot of shade over backend processes these days, especially in the land of JavaScript. Originally a language targeting browsers, JS has matured into every nook and cranny of modern development as a de facto tool. The syntax for interacting with various libraries in JavaScript can be confusingly identical between front-end and backend environments, so it helps to have a clear picture of what is going on. We’ll discuss the context briefly below, and then I’ll end with my own recipe for you to upload files with node.
The Problem: Information Overload
Searching for “JavaScript File Uploads" will yield an abundance of results, but it can be hard to tell at first glance which practical examples are targeting your specific needs. SDKs often don’t care that much they’re run, so it is up to the developer to clearly understand the nuances involved.

Link: https://dzone.com/articles/upload-files-with-node?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Build a Simple REST API with Node and OAuth 2.0

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
JavaScript is used everywhere on the web – nearly every web page will include at least some JavaScript, and even if it doesn’t, your browser probably has some sort of extension that injects bits of JavaScript code on to the page anyway. It’s hard to avoid in 2018.
JavaScript can also be used outside the context of a browser, for anything from hosting a web server to controlling an RC car or running a full-fledged operating system. Sometimes you want a couple of servers to talk to each other, whether on a local network or over the internet.
Today, I’ll show you how to create a REST API using Node.js, and secure it with OAuth 2.0 to prevent unwarranted requests. REST APIs are all over the web, but without the proper tools require a ton of boilerplate code. I’ll show you how to use a couple of amazing tools that make it all a breeze, including Okta to implement the Client Credentials Flow, which securely connects two machines together without the context of a user.
Build Your Node Server
Setting up a web server in Node is quite simple using the Express JavaScript library. Make a new folder that will contain your server.
$ mkdir rest-api

Node uses a package.json to manage dependencies and define your project. To create one, use npm init, which will ask you some questions to help you initialize the project. For now, you can use standard JS to enforce a coding standard, and use that as the tests.
$ cd rest-api

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (rest-api)
version: (1.0.0)
description: A parts catalog
entry point: (index.js)
test command: standard
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/Braden/code/rest-api/package.json:

{
“name": "rest-api",
"version": "1.0.0",
"description": "A parts catalog",
"main": "index.js",
"scripts": {
"test": "standard"
},
"author": "",
"license": "ISC"
}

Is this OK? (yes)

The default entry point is index.js, so you should create a new file by that name. The following code will get you a really basic server that doesn’t really do anything but listens on port 3000 by default.
index.js
const express = require(‘express’)
const bodyParser = require(‘body-parser’)
const { promisify } = require(‘util’)

const app = express()
app.use(bodyParser.json())

const startServer = async () => {
const port = process.env.SERVER_PORT || 3000
await promisify(app.listen).bind(app)(port)
console.log(`Listening on port ${port}`)
}

startServer()

The promisify function of util lets you take a function that expects a callback and instead will return a Promise, which is the new standard as far as handling asynchronous code. This also lets us use the relatively new async/await syntax and make our code look much prettier.
In order for this to work, you need to install the dependencies that you require at the top of the file. Add them using npm install. This will automatically save some metadata to your package.json file and install them locally in a node_modules folder.
Note: You should never commit node_modules to source control because it tends to become bloated quickly, and the package-lock.json file will keep track of the exact versions you used to that if you install this on another machine they get the same code.
$ npm install express@4.16.3 util@0.11.0

For some quick linting, install standard as a dev dependency, then run it to make sure your code is up to par.
$ npm install –save-dev standard@11.0.1
$ npm test

> rest-api@1.0.0 test /Users/bmk/code/okta/apps/rest-api
> standard

If all is well, you shouldn’t see any output past the > standard line. If there’s an error, it might look like this:
$ npm test

> rest-api@1.0.0 test /Users/bmk/code/okta/apps/rest-api
> standard

standard: Use JavaScript Standard Style (https://standardjs.com)
standard: Run `standard –fix` to automatically fix some problems.
/Users/Braden/code/rest-api/index.js:3:7: Expected consistent spacing
/Users/Braden/code/rest-api/index.js:3:18: Unexpected trailing comma.
/Users/Braden/code/rest-api/index.js:3:18: A space is required after ‘,’.
/Users/Braden/code/rest-api/index.js:3:38: Extra semicolon.
npm ERR! Test failed. See above for more details.

Now that your code is ready and you have installed your dependencies, you can run your server with node . (the . says to look at the current directory, and then checks your package.json file to see that the main file to use in this directory is index.js):
$ node .

Listening on port 3000

To test that it’s working, you can use the curl command. There are no endpoints yet, so express will return an error:
$ curl localhost:3000 -i
HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Security-Policy: default-src ‘self’
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 139
Date: Thu, 16 Aug 2018 01:34:53 GMT
Connection: keep-alive

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /</pre>
</body>
</html>

Even though it says it’s an error, that’s good. You haven’t set up any endpoints yet, so the only thing for Express to return is a 404 error. If your server wasn’t running at all, you’d get an error like this:
$ curl localhost:3000 -i
curl: (7) Failed to connect to localhost port 3000: Connection refused

Build Your REST API with Express, Sequelize, and Epilogue
Now that you have a working Express server, you can add a REST API. This is actually much simpler than you might think. The easiest way I’ve seen is by using Sequelize to define your database schema, and Epilogue to create some REST API endpoints with near-zero boilerplate.
You’ll need to add those dependencies to your project. Sequelize also needs to know how to communicate with the database. For now, use SQLite as it will get us up and running quickly.
npm install sequelize@4.38.0 epilogue@0.7.1 sqlite3@4.0.2

Create a new file database.js with the following code. I’ll explain each part in more detail below.
database.js
const Sequelize = require(‘sequelize’)
const epilogue = require(‘epilogue’)

const database = new Sequelize({
dialect: ‘sqlite’,
storage: ‘./test.sqlite’,
operatorsAliases: false
})

const Part = database.define(‘parts’, {
partNumber: Sequelize.STRING,
modelNumber: Sequelize.STRING,
name: Sequelize.STRING,
description: Sequelize.TEXT
})

const initializeDatabase = async (app) => {
epilogue.initialize({ app, sequelize: database })

epilogue.resource({
model: Part,
endpoints: [‘/parts’, ‘/parts/:id’]
})

await database.sync()
}

module.exports = initializeDatabase

Now you just need to import that file into your main app and run the initialization function. Make the following additions to your index.js file.
index.js
@@ -2,10 +2,14 @@ const express = require(‘express’)
const bodyParser = require(‘body-parser’)
const { promisify } = require(‘util’)

+const initializeDatabase = require(‘./database’)
+
const app = express()
app.use(bodyParser.json())

const startServer = async () => {
+ await initializeDatabase(app)
+
const port = process.env.SERVER_PORT || 3000
await promisify(app.listen).bind(app)(port)
console.log(`Listening on port ${port}`)

You can now test for syntax errors and run the app if everything seems good:
$ npm test && node .

> rest-api@1.0.0 test /Users/bmk/code/okta/apps/rest-api
> standard

Executing (default): CREATE TABLE IF NOT EXISTS `parts` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `partNumber` VARCHAR(255), `modelNu
mber` VARCHAR(255), `name` VARCHAR(255), `description` TEXT, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);
Executing (default): PRAGMA INDEX_LIST(`parts`)
Listening on port 3000

In another terminal, you can test that this is actually working (to format the JSON response I use a json CLI, installed globally using npm install –global json):
$ curl localhost:3000/parts
[]

$ curl localhost:3000/parts -X POST -d ‘{
"partNumber": "abc-123",
"modelNumber": "xyz-789",
"name": "Alphabet Soup",
"description": "Soup with letters and numbers in it"
}’ -H ‘content-type: application/json’ -s0 | json
{
"id": 1,
"partNumber": "abc-123",
"modelNumber": "xyz-789",
"name": "Alphabet Soup",
"description": "Soup with letters and numbers in it",
"updatedAt": "2018-08-16T02:22:09.446Z",
"createdAt": "2018-08-16T02:22:09.446Z"
}

$ curl localhost:3000/parts -s0 | json
[
{
"id": 1,
"partNumber": "abc-123",
"modelNumber": "xyz-789",
"name": "Alphabet Soup",
"description": "Soup with letters and numbers in it",
"createdAt": "2018-08-16T02:22:09.446Z",
"updatedAt": "2018-08-16T02:22:09.446Z"
}
]

What’s Going On Here?
Feel free to skip this section if you followed along with all that, but I did promise an explanation.
The Sequelize function creates a database. This is where you configure details, such as what dialect of SQL to use. For now, use SQLite to get up and running quickly.
const database = new Sequelize({
dialect: ‘sqlite’,
storage: ‘./test.sqlite’,
operatorsAliases: false
})

Once you’ve created the database, you can define the schema for it using database.define for each table. Create a table called parts with a few useful fields to keep track of parts. By default, Sequelize also automatically creates and updates id, createdAt, and updatedAt fields when you create or update a row.
const Part = database.define(‘parts’, {
partNumber: Sequelize.STRING,
modelNumber: Sequelize.STRING,
name: Sequelize.STRING,
description: Sequelize.TEXT
})

Epilogue requires access to your Express app in order to add endpoints. However, app is defined in another file. One way to deal with this is to export a function that takes the app and does something with it. In the other file when we import this script, you would run it like initializeDatabase(app).
Epilogue needs to initialize with both the app and the database. You then define which REST endpoints you would like to use. The resource function will include endpoints for the GET, POST, PUT, and DELETE verbs, mostly automagically.
To actually create the database, you need to run database.sync(), which returns a Promise. You’ll want to wait until it’s finished before starting your server.
The module.exports command says that the initializeDatabase function can be imported from another file.
const initializeDatabase = async (app) => {
epilogue.initialize({ app, sequelize: database })

epilogue.resource({
model: Part,
endpoints: [‘/parts’, ‘/parts/:id’]
})

await database.sync()
}

module.exports = initializeDatabase

Secure Your Node + Express REST API with OAuth 2.0
Now that you have a REST API up and running, imagine you’d like a specific application to use this from a remote location. If you host this on the internet as is, then anybody can add, modify, or remove parts at their will.
To avoid this, you can use the OAuth 2.0 Client Credentials Flow. This is a way of letting two servers communicate with each other, without the context of a user. The two servers must agree ahead of time to use a third-party authorization server. Assume there are two servers, A and B, and an authorization server. Server A is hosting the REST API, and Server B would like to access the API.

Server B sends a secret key to the authorization server to prove who they are and asks for a temporary token.
Server B then consumes the REST API as usual but sends the token along with the request.
Server A asks the authorization server for some metadata that can be used to verify tokens.
Server A verifies the Server B’s request.

If it’s valid, a successful response is sent and Server B is happy.
If the token is invalid, an error message is sent instead, and no sensitive information is leaked.

Create an Authorization Server
This is where Okta comes into play. Okta can act as an authorization server to allow you to secure your data. You’re probably asking yourself “Why Okta? Well, it’s pretty cool to build a REST app, but it’s even cooler to build a secure one. To achieve that, you’ll want to add authentication so users have to log in before viewing/modifying groups. At Okta, our goal is to make identity management a lot easier, more secure, and more scalable than what you’re used to. Okta is a cloud service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. Our API enables you to:

Authenticate and authorize your users
Store data about your users
Perform password-based and social login
Secure your application with multi-factor authentication
And much more! Check out our product documentation

If you don’t already have one, sign up for a forever-free developer account, and let’s get started!
After creating your account, log in to your developer console, navigate to API, then to the Authorization Servers tab. Click on the link to your default server.
From this Settings tab, copy the Issuer field. You’ll need to save this somewhere that your Node app can read. In your project, create a file named .env that looks like this:
.env
ISSUER=https://{yourOktaDomain}/oauth2/default

The value for ISSUER should be the value from the Settings page’s Issuer URI field.

Note: As a general rule, you should not store this .env file in source control. This allows multiple projects to use the same source code without needing a separate fork. It also makes sure that your secure information is not public (especially if you’re publishing your code as open source).
Next, navigate to the Scopes tab. Click the Add Scope button and create a scope for your REST API. You’ll need to give it a name (e.g. parts_manager) and you can give it a description if you like.

You should add the scope name to your .env file as well so your code can access it.
.env
ISSUER=https://{yourOktaDomain}/oauth2/default
SCOPE=parts_manager

Now you need to create a client. Navigate to Applications, then click Add Application. Select Service, then click Next. Enter a name for your service, (e.g. Parts Manager), then click Done.
The post Build a Simple REST API with Node and OAuth 2.0 appeared first on SitePoint.

Link: https://developer.okta.com/blog/2018/08/21/build-secure-rest-api-with-node

Achieve: JavaScript Servlets on Node.js

Achieve is a modern HTTP server that runs on Node.js and uses JavaScript Servlets to initiate backend processing. (npm, GitHub) JS Servlets are fast, very easy to use, and do not limit your ability to develop sophisticated backend applications; perfect for the rapid development of microservices or complete Node.js-based web applications. You can even use it just to serve web pages.
A servlet is a small program that runs on a server. The term has long since been associated with Java. Java Servlets provide the interface between servers and backend application programs written in Java. This new server implementation, named Achieve, provides a JavaScript Servlet implementation on Node.js. If you are familiar with Java Servlets, you should easily see general similarities in the new JS Servlet design.

Link: https://dzone.com/articles/achieve-javascript-servlets-on-nodejs?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

A Look Into Node.js

Recently, I came across an interesting snippet of data about Node.js: it is being utilized by a some of the greatest worldwide associations including NASA, Airbnb, PayPal, LinkedIn, Netflix, Uber, and Walmart. Actually, 98% of Fortune 500 companies utilize Node.js on a regular basis. It is certainly overwhelming the market and for good reason.

Link: https://dzone.com/articles/a-look-into-nodejs?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

React Image Upload: How It’s Done

File upload is a very important feature of web applications: it helps facilitate actions like setting a user’s profile picture, setting up dynamic galleries, remote file storage, and file sharing, among many other functionalities. In this article, we will be looking at file upload (more specifically, images), using the React web framework, and a Node.js Express backend server.
Here is the application we are going to be building:

Link: https://dzone.com/articles/react-image-upload-how-its-done?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Angular on PCF and Other Production Servers

Background
Angular has become the primary choice for developers to build a web and SPA application. However, most of the tutorials available talk about running the Angular app using “ng serve." "ng serve" is a command provided by the AngularJS CLI. It will  serve a project that is ‘Angular CLI aware,’ i.e. a project that has been created using the Angular CLI,  particularly using:  ng new app-name 
This is useful when you are developing the app on your system and want to see the changes reflected in browser while coding. However, once the application is ready to deploy, you’ll need to host it on a web server like Node.js or NGINX. PCF also supports buildback for nodejs and nginx.

Link: https://dzone.com/articles/angularjs-on-production-server?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Build a Health Tracking App with React, GraphQL, and User Authentication

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
I think you’ll like the story I’m about to tell you. I’m going to show you how to build a GraphQL API with Vesper framework, TypeORM, and MySQL. These are Node frameworks, and I’ll use TypeScript for the language. For the client, I’ll use React, reactstrap, and Apollo Client to talk to the API. Once you have this environment working, and you add secure user authentication, I believe you’ll love the experience!
Why focus on secure authentication? Well, aside from the fact that I work for Okta, I think we can all agree that pretty much every application depends upon a secure identity management system. For most developers who are building React apps, there’s a decision to be made between rolling your own authentication/authorization or plugging in a service like Okta. Before I dive into building a React app, I want to tell you a bit about Okta, and why I think it’s an excellent solution for all JavaScript developers.
What Is Okta?
In short, we make identity management a lot easier, more secure, and more scalable than what you’re used to. Okta is a cloud service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. Our API enables you to:

Authenticate and authorize your users
Store data about your users
Perform password-based and social login
Secure your application with multi-factor authentication
And much more! Check out our product documentation

Are you sold? Register for a forever-free developer account, and when you’re done, come on back so we can learn more about building secure apps in React!
Why a Health Tracking App?
In late September through mid-October 2014, I’d done a 21-Day Sugar Detox during which I stopped eating sugar, started exercising regularly, and stopped drinking alcohol. I’d had high blood pressure for over ten years and was on blood pressure medication at the time. During the first week of the detox, I ran out of blood pressure medication. Since a new prescription required a doctor visit, I decided I’d wait until after the detox to get it. After three weeks, not only did I lose 15 pounds, but my blood pressure was at normal levels!
Before I started the detox, I came up with a 21-point system to see how healthy I was each week. Its rules were simple: you can earn up to three points per day for the following reasons:

If you eat healthy, you get a point. Otherwise, zero.
If you exercise, you get a point.
If you don’t drink alcohol, you get a point.

I was surprised to find I got eight points the first week I used this system. During the detox, I got 16 points the first week, 20 the second, and 21 the third. Before the detox, I thought eating healthy meant eating anything except fast food. After the detox, I realized that eating healthy for me meant eating no sugar. I’m also a big lover of craft beer, so I modified the alcohol rule to allow two healthier alcohol drinks (like a greyhound or red wine) per day.
My goal is to earn 15 points per week. I find that if I get more, I’ll likely lose weight and have good blood pressure. If I get fewer than 15, I risk getting sick. I’ve been tracking my health like this since September 2014. I’ve lost weight, and my blood pressure has returned to and maintained normal levels. I haven’t had good blood pressure since my early 20s, so this has been a life-changer for me.
I built 21-Points Health to track my health. I figured it’d be fun to recreate a small slice of that app, just tracking daily points.
Building an API with TypeORM, GraphQL, and Vesper
TypeORM is a nifty ORM (object-relational mapper) framework that can run in most JavaScript platforms, including Node, a browser, Cordova, React Native, and Electron. It’s heavily influenced by Hibernate, Doctrine, and Entity Framework. Install TypeORM globally to begin creating your API.
npm i -g typeorm@0.2.7

Create a directory to hold the React client and GraphQL API.
mkdir health-tracker
cd health-tracker

Create a new project with MySQL using the following command:
typeorm init –name graphql-api –database mysql

Edit graphql-api/ormconfig.json to customize the username, password, and database.
{

“username": "health",
"password": "pointstest",
"database": "healthpoints",

}

TIP: To see the queries being executed against MySQL, change the “logging” value in this file to be “all”. Many other logging options are available too.
Install MySQL
Install MySQL if you don’t already have it installed. On Ubuntu, you can use sudo apt-get install mysql-server. On macOS, you can use Homebrew and brew install mysql. For Windows, you can use the MySQL Installer.
Once you’ve got MySQL installed and configured with a root password, login and create a healthpoints database.
mysql -u root -p
create database healthpoints;
use healthpoints;
grant all privileges on *.* to ‘health’@’localhost’ identified by ‘points’;

Navigate to your graphql-api project in a terminal window, install the project’s dependencies, then start it to ensure you can connect to MySQL.
cd graphql-api
npm i
npm start

You should see the following output:
Inserting a new user into the database…
Saved a new user with id: 1
Loading users from the database…
Loaded users: [ User { id: 1, firstName: ‘Timber’, lastName: ‘Saw’, age: 25 } ]
Here you can setup and run express/koa/any other framework.

Install Vesper to Integrate TypeORM and GraphQL
Vesper is a Node framework that integrates TypeORM and GraphQL. To install it, use good ol’ npm.
npm i vesper@0.1.9

Now it’s time to create some GraphQL models (that define what your data looks like) and some controllers (that explain how to interact with your data).
Create graphql-api/src/schema/model/Points.graphql:
type Points {
id: Int
date: Date
exercise: Int
diet: Int
alcohol: Int
notes: String
user: User
}

Create graphql-api/src/schema/model/User.graphql:
type User {
id: String
firstName: String
lastName: String
points: [Points]
}

Next, create a graphql-api/src/schema/controller/PointsController.graphql with queries and mutations:
type Query {
points: [Points]
pointsGet(id: Int): Points
users: [User]
}

type Mutation {
pointsSave(id: Int, date: Date, exercise: Int, diet: Int, alcohol: Int, notes: String): Points
pointsDelete(id: Int): Boolean
}

Now that your data has GraphQL metadata create entities that will be managed by TypeORM. Change src/entity/User.ts to have the following code that allows points to be associated with a user.
import { Column, Entity, OneToMany, PrimaryColumn } from ‘typeorm’;
import { Points } from ‘./Points’;

@Entity()
export class User {

@PrimaryColumn()
id: string;

@Column()
firstName: string;

@Column()
lastName: string;

@OneToMany(() => Points, points => points.user)
points: Points[];
}

In the same src/entity directory, create a Points.ts class with the following code.
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from ‘typeorm’;
import { User } from ‘./User’;

@Entity()
export class Points {

@PrimaryGeneratedColumn()
id: number;

@Column({ type: ‘timestamp’, default: () => ‘CURRENT_TIMESTAMP’})
date: Date;

@Column()
exercise: number;

@Column()
diet: number;

@Column()
alcohol: number;

@Column()
notes: string;

@ManyToOne(() => User, user => user.points, { cascade: ["insert"] })
user: User|null;
}

Note the cascade: ["insert"] option on the @ManyToOne annotation above. This option will automatically insert a user if it’s present on the entity. Create src/controller/PointsController.ts to handle converting the data from your GraphQL queries and mutations.
import { Controller, Mutation, Query } from ‘vesper’;
import { EntityManager } from ‘typeorm’;
import { Points } from ‘../entity/Points’;

@Controller()
export class PointsController {

constructor(private entityManager: EntityManager) {
}

// serves "points: [Points]" requests
@Query()
points() {
return this.entityManager.find(Points);
}

// serves "pointsGet(id: Int): Points" requests
@Query()
pointsGet({id}) {
return this.entityManager.findOne(Points, id);
}

// serves "pointsSave(id: Int, date: Date, exercise: Int, diet: Int, alcohol: Int, notes: String): Points" requests
@Mutation()
pointsSave(args) {
const points = this.entityManager.create(Points, args);
return this.entityManager.save(Points, points);
}

// serves "pointsDelete(id: Int): Boolean" requests
@Mutation()
async pointsDelete({id}) {
await this.entityManager.remove(Points, {id: id});
return true;
}
}

Change src/index.ts to use Vesper’s bootstrap() to configure everything.
import { bootstrap } from ‘vesper’;
import { PointsController } from ‘./controller/PointsController’;
import { Points } from ‘./entity/Points’;
import { User } from ‘./entity/User’;

bootstrap({
port: 4000,
controllers: [
PointsController
],
entities: [
Points,
User
],
schemas: [
__dirname + ‘/schema/**/*.graphql’
],
cors: true
}).then(() => {
console.log(‘Your app is up and running on http://localhost:4000. ‘ +
‘You can use playground in development mode on http://localhost:4000/playground’);
}).catch(error => {
console.error(error.stack ? error.stack : error);
});

This code tells Vesper to register controllers, entities, GraphQL schemas, to run on port 4000, and to enable CORS (cross-origin resource sharing).
Start your API using npm start and navigate to http://localhost:4000/playground. In the left pane, enter the following mutation and press the play button. You might try typing the code below so you can experience the code completion that GraphQL provides you.
mutation {
pointsSave(exercise:1, diet:1, alcohol:1, notes:"Hello World") {
id
date
exercise
diet
alcohol
notes
}
}

Your result should look similar to mine.

You can click the “SCHEMA” tab on the right to see the available queries and mutations. Pretty slick, eh?!
You can use the following points query to verify that data is in your database.
query {
points {id date exercise diet notes}
}

Fix Dates
You might notice that the date returned from pointsSave and the points query is in a format the might be difficult for a JavaScript client to understand. You can fix that, install graphql-iso-date.
npm i graphql-iso-date@3.5.0

Then, add an import in src/index.ts and configure custom resolvers for the various date types. This example only uses Date, but it’s helpful to know the other options.
import { GraphQLDate, GraphQLDateTime, GraphQLTime } from ‘graphql-iso-date’;

bootstrap({

// https://github.com/vesper-framework/vesper/issues/4
customResolvers: {
Date: GraphQLDate,
Time: GraphQLTime,
DateTime: GraphQLDateTime
},

});

Now running the points query will return a more client-friendly result.
{
"data": {
"points": [
{
"id": 1,
"date": "2018-06-04",
"exercise": 1,
"diet": 1,
"notes": "Hello World"
}
]
}
}

You’ve written an API with GraphQL and TypeScript in about 20 minutes. How cool is that?! There’s still work to do though. In the next sections, you’ll create a React client for this API and add authentication with OIDC. Adding authentication will give you the ability to get the user’s information and associate a user with their points.
Get Started with React
One of the quickest ways to get started with React is to use Create React App. Install the latest release using the command below.
npm i -g create-react-app@1.1.4

Navigate to the directory where you created your GraphQL API and create a React client.
cd health-tracker
create-react-app react-client

Install the dependencies you’ll need to talk to integrate Apollo Client with React, as well as Bootstrap and reactstrap.
npm i apollo-boost@0.1.7 react-apollo@2.1.4 graphql-tag@2.9.2 graphql@0.13.2

Configure Apollo Client for Your API
Open react-client/src/App.js and import ApolloClient from apollo-boost and add the endpoint to your GraphQL API.
import ApolloClient from ‘apollo-boost’;

const client = new ApolloClient({
uri: "http://localhost:4000/graphql"
});

That’s it! With only three lines of code, your app is ready to start fetching data. You can prove it by importing the gql function from graphql-tag. This will parse your query string and turn it into a query document.
import gql from ‘graphql-tag’;

class App extends Component {

componentDidMount() {
client.query({
query: gql`
{
points {
id date exercise diet alcohol notes
}
}
`
})
.then(result => console.log(result));
}

}

Make sure to open your browser’s developer tools so you can see the data after making this change. You could modify the console.log() to use this.setState({points: results.data.points}), but then you’d have to initialize the default state in the constructor. But there’s an easier way: you can use ApolloProvider and Query components from react-apollo!
Below is a modified version of react-client/src/App.js that uses these components.
import React, { Component } from ‘react’;
import logo from ‘./logo.svg’;
import ‘./App.css’;
import ApolloClient from ‘apollo-boost’;
import gql from ‘graphql-tag’;
import { ApolloProvider, Query } from ‘react-apollo’;
const client = new ApolloClient({
uri: "http://localhost:4000/graphql"
});

class App extends Component {

render() {
return (

<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<Query query={gql`
{
points {id date exercise diet alcohol notes}
}
`}>
{({loading, error, data}) => {
if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error}</p>;
return data.points.map(p => {
return <div key={p.id}>
<p>Date: {p.date}</p>
<p>Points: {p.exercise + p.diet + p.alcohol}</p>
<p>Notes: {p.notes}</p>
</div>
})
}}
</Query>
</div>
</ApolloProvider>
);
}
}

export default App;

You’ve built a GraphQL API and a React UI that talks to it – excellent work! However, there’s still more to do. In the next sections, I’ll show you how to add authentication to React, verify JWTs with Vesper, and add CRUD functionality to the UI. CRUD functionality already exists in the API thanks to the mutations you wrote earlier.
Add Authentication for React with OpenID Connect
You’ll need to configure React to use Okta for authentication. You’ll need to create an OIDC app in Okta for that.
Log in to your Okta Developer account (or sign up if you don’t have an account) and navigate to Applications > Add Application. Click Single-Page App, click Next, and give the app a name you’ll remember. Change all instances of localhost:8080 to localhost:3000 and click Done. Your settings should be similar to the screenshot below.

Okta’s React SDK allows you to integrate OIDC into a React application. To install, run the following commands:
npm i @okta/okta-react@1.0.2 react-router-dom@4.2.2

Okta’s React SDK depends on react-router, hence the reason for installing react-router-dom. Configuring routing in client/src/App.tsx is a common practice, so replace its code with the JavaScript below that sets up authentication with Okta.
import React, { Component } from ‘react’;
import { BrowserRouter as Router, Route } from ‘react-router-dom’;
import { ImplicitCallback, SecureRoute, Security } from ‘@okta/okta-react’;
import Home from ‘./Home’;
import Login from ‘./Login’;
import Points from ‘./Points’;

function onAuthRequired({history}) {
history.push(‘/login’);
}

class App extends Component {
render() {
return (
<Router>
<Security issuer=’https://{yourOktaDomain}/oauth2/default’
client_id='{clientId}’
redirect_uri={window.location.origin + ‘/implicit/callback’}
onAuthRequired={onAuthRequired}>
<Route path=’/’ exact={true} component={Home}/>
<SecureRoute path=’/points’ component={Points}/>
<Route path=’/login’ render={() => <Login baseUrl=’https://{yourOktaDomain}’/>}/>
<Route path=’/implicit/callback’ component={ImplicitCallback}/>
</Security>
</Router>
);
}
}

export default App;

Make sure to replace {yourOktaDomain} and {clientId} in the code above. You can find both values in the Okta Developer Console.
The code in App.js references two components that don’t exist yet: Home, Login, and Points. Create src/Home.js with the following code. This component renders the default route, provides a Login button, and links to your points and logout after you’ve logged in.
import React, { Component } from ‘react’;
import { withAuth } from ‘@okta/okta-react’;
import { Button, Container } from ‘reactstrap’;
import AppNavbar from ‘./AppNavbar’;
import { Link } from ‘react-router-dom’;

export default withAuth(class Home extends Component {
constructor(props) {
super(props);
this.state = {authenticated: null, userinfo: null, isOpen: false};
this.checkAuthentication = this.checkAuthentication.bind(this);
this.checkAuthentication();
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
}

async checkAuthentication() {
const authenticated = await this.props.auth.isAuthenticated();
if (authenticated !== this.state.authenticated) {
if (authenticated && !this.state.userinfo) {
const userinfo = await this.props.auth.getUser();
this.setState({authenticated, userinfo});
} else {
this.setState({authenticated});
}
}
}

async componentDidMount() {
this.checkAuthentication();
}

async componentDidUpdate() {
this.checkAuthentication();
}

async login() {
this.props.auth.login(‘/’);
}

async logout() {
this.props.auth.logout(‘/’);
this.setState({authenticated: null, userinfo: null});
}

render() {
if (this.state.authenticated === null) return null;
const button = this.state.authenticated ?
<div>
<Button color="link"><Link to="/points">Manage Points</Link></Button><br/>
<Button color="link" onClick={this.logout}>Logout</Button>
</div>:
<Button color="primary" onClick={this.login}>Login</Button>;

const message = this.state.userinfo ?
<p>Hello, {this.state.userinfo.given_name}!</p> :
<p>Please log in to manage your points.</p>;

return (
<div>
<AppNavbar/>
<Container fluid>
{message}
{button}
</Container>
</div>
);
}
});

This component uses <Container/> and <Button/> from reactstrap. Install reactstrap, so everything compiles. It depends on Bootstrap, so include it too.
npm i reactstrap@6.1.0 bootstrap@4.1.1

Add Bootstrap’s CSS file as an import in src/index.js.
The post Build a Health Tracking App with React, GraphQL, and User Authentication appeared first on SitePoint.

Link: https://developer.okta.com/blog/2018/07/11/build-react-graphql-api-user-authentication

Functional Programming Unit Testing in Node (Part 6)

Welcome to Part 6, the final installment in this series. Below we cover unit testing the noop next, how to create pure functions that wrap noop so you can compose them, and finally using code coverage to strategically hit the last code that’s not covered.
Content
This is a 6 part series on refactoring imperative code in Node to a functional programming style with unit tests. You are currently on Part 6.

Link: https://dzone.com/articles/functional-programming-unit-testing-in-node-part-6?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Running PM2 and Node.js in Production Environments

At Stream, we build a lot of showcase and example applications to show off the awesome features that our service has to offer. For nearly all of our applications, we host them on an instance – usually DigitalOcean or AWS EC2.
While maintaining your codebase and keeping it relevant is difficult, we’ve found that the most challenging aspect when it comes to maintaining an application is keeping it alive and running. Additionally, with Node.js being the core language for most of our backend APIs, scaling a single threaded process can be hard to do; that’s where PM2 comes in and why we enjoy using it so much.

Link: https://dzone.com/articles/running-pm2-amp-nodejs-in-production-environments?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev