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

Calls between JavaScript and WebAssembly are finally fast 🎉

At Mozilla, we want WebAssembly to be as fast as it can be. This started with its design, which gives it great throughput. Then we improved load times with a streaming baseline compiler. With this, we compile code faster than it comes over the network. Now, in the latest version of Firefox Beta, calls between JS and WebAssembly are faster than many JS to JS function calls. Here’s how we made them fast – illustrated in code cartoons.
The post Calls between JavaScript and WebAssembly are finally fast 🎉 appeared first on Mozilla Hacks – the Web developer blog.

Link: https://hacks.mozilla.org/2018/10/calls-between-javascript-and-webassembly-are-finally-fast-%f0%9f%8e%89/

How to Get and Set CSS Variable Values with JavaScript

CSS variables are a very welcome addition to the language, despite them being incredibly basic.  Sure we could use SASS or stylus but languages should never count on developers relying on frameworks and toolkits to accomplish what we know we need.  And just like every other part of a webpage, you can get and manipulate […]
The post How to Get and Set CSS Variable Values with JavaScript appeared first on David Walsh Blog.

Link: https://davidwalsh.name/css-variables-javascript

The Evolution of the JavaScript Programming Language

When you look around the software development world today, one language that seems to be everywhere is JavaScript. JavaScript has gained a lot of popularity over the years, and, despite facing various stumbling blocks, this language has gone on to become the most popular language in the world today.
For this reason, I am interested in the evolution of the language. The low points, high points, and its strength. Without further ado, let’s dive into it.

Link: https://dzone.com/articles/evolution-of-javascript-programming-language?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Build a Simple API Service with Express and GraphQL

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
GraphQL has become an immensely popular alternative to REST APIs. The flexibility you get from using GraphQL makes it easier for developers to get any information they need for an app, and just the information they need for that portion of the app. That gives you the feel of a very customized API and can help cut down on bandwidth.
In this tutorial, I’ll show you how to write a custom GraphQL API using Node and Express. I’ll also show you how to secure parts of the API while making other parts open to the public.
Create the GraphQL API with Express
To create the API, start by creating a new folder and creating a package.json file to manage your dependencies. You’ll also need to install a few dependencies to get GraphQL with Express up and running:
mkdir graphql-express
cd graphql-express
npm init -y
npm install express@2.8.4 express-graphql@0.6.12 graphql@14.0.2 graphql-tag@2.9.2 cors@2.8.4

Now create a file named index.js. This will be your main entry point:
const express = require(‘express’)
const cors = require(‘cors’)
const graphqlHTTP = require(‘express-graphql’)
const gql = require(‘graphql-tag’)
const { buildASTSchema } = require(‘graphql’)

const app = express()
app.use(cors())

const schema = buildASTSchema(gql`
type Query {
hello: String
}
`)

const rootValue = {
hello: () => ‘Hello, world’
}

app.use(‘/graphql’, graphqlHTTP({ schema, rootValue }))

const port = process.env.PORT || 4000
app.listen(port)
console.log(`Running a GraphQL API server at localhost:${port}/graphql`)

This is about as simple as a GraphQL server gets. All this does is return “Hello, world” when you query “hello”, but it’s a start. To take it for a test spin, run node ., then in another tab open your browser to the GraphQL Playground. Once there, enter http://localhost:4000/graphql to access your GraphQL server.

The GraphQL Playground will help explore your schema and test out queries. It even automatically creates some documentation for you.

Try querying for hello using the following query:
query {
hello
}

Improve Your GraphQL Developer Experience
Here are a couple quick tips to help make your development experience a little better:
1. Install a linter to help catch bugs in your editor. This will help keep your styling consistent and catch any easily-avoidable bugs.
To install StandardJS, type npm install –save-dev standard@12.0.1. Most editors will be able to show you warnings and errors as you type.
You can also edit the scripts object of your package.json so that you can run the linter at any time with npm test:
“scripts": {
"test": "standard"
},

2. Automatically restart the server when you make changes.
Install nodemon with npm install –save-dev nodemon@1.18.4.
Add another script to package.json, so you can run the server with npm start. Combined with the above, your scripts object should look like this:
"scripts": {
"test": "standard",
"start": "nodemon ."
},

Go ahead and close the server you had run with node . and now type npm start to restart the development server. From now on, any changes you make will automatically restart the server.
Create the GraphQL Queries
To get something a little more useful, let’s make a post editor. GraphQL is strongly typed, allowing you to create a type for each object and connect them. A common scenario might be to have a post with some text, that was written by a person. Update your schema to include these types. You can also update your Query type to utilize these new types.
type Query {
posts: [Post]
post(id: ID): Post
authors: [Person]
author(id: ID): Person
}

type Post {
id: ID
author: Person
body: String
}

type Person {
id: ID
posts: [Post]
firstName: String
lastName: String
}

Even though the resolvers aren’t set up, you can already go back to GraphQL Playground and refresh the schema by clicking the circular arrow icon next to the localhost URL.

The schema explorer is really useful for figuring out how to create your query. Click the green SCHEMA button to check out your new schema.

You’ll need some way to store the data. To keep it simple, use JavaScript’s Map object for in-memory storage. You can also create some classes that will help connect the data from one object to another.
const PEOPLE = new Map()
const POSTS = new Map()

class Post {
constructor (data) { Object.assign(this, data) }
get author () {
return PEOPLE.get(this.authorId)
}
}

class Person {
constructor (data) { Object.assign(this, data) }
get posts () {
return […POSTS.values()].filter(post => post.authorId === this.id)
}
}

Now if you have an instance of a Person, you can find all of their posts by simply asking for person.posts. Since GraphQL lets you only ask for the data you want, the posts getter will never get called unless you ask for it, which could speed up the query if that’s an expensive operation.
You’ll also need to update your resolvers (the functions in rootValue) in order to accommodate these new types.
const rootValue = {
posts: () => POSTS.values(),
post: ({ id }) => POSTS.get(id),
authors: () => PEOPLE.values(),
author: ({ id }) => PEOPLE.get(id)
}

This is great, but there’s no data yet. For now, stub in some fake data. You can add this function and the call to it right after the assignment to rootValue.
const initializeData = () => {
const fakePeople = [
{ id: ‘1’, firstName: ‘John’, lastName: ‘Doe’ },
{ id: ‘2’, firstName: ‘Jane’, lastName: ‘Doe’ }
]

fakePeople.forEach(person => PEOPLE.set(person.id, new Person(person)))

const fakePosts = [
{ id: ‘1’, authorId: ‘1’, body: ‘Hello world’ },
{ id: ‘2’, authorId: ‘2’, body: ‘Hi, planet!’ }
]

fakePosts.forEach(post => POSTS.set(post.id, new Post(post)))
}

initializeData()

Now that you have your queries all set up and some data stubbed in, go back to GraphQL Playground and play around a bit. Try getting all the posts, or get all the authors and posts associated with each one.

Or get weird and get a single post by id, then the author for that post, and all of that author’s posts (including the one you just queried).

Add User Authentication to Your Express + GraphQL API
One simple way to add authentication to your project is with Okta. 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. If you don’t already have one, sign up for a forever-free developer account.
You’re going to need to save some information to use in the app. Create a new file named .env. In it, enter in your organization URL.
HOST_URL=http://localhost:4000
OKTA_ORG_URL=https://{yourOktaOrgUrl}

You will also need a random string to use as an App Secret for sessions. You can generate this with the following command:
echo "APP_SECRET=`openssl rand -base64 32`" >> .env

Next, log in to your developer console, navigate to Applications, then click Add Application. Select Web, then click Next.

The page you come to after creating an application has some more information you need to save to your .env file. Copy in the client ID and client secret.
OKTA_CLIENT_ID={yourClientId}
OKTA_CLIENT_SECRET={yourClientSecret}

The last piece of information you need from Okta is an API token. In your developer console, navigate to API -> Tokens, then click on Create Token. You can have many tokens, so just give this one a name that reminds you what it’s for, like “GraphQL Express”. You’ll be given a token that you can only see right now. If you lose the token, you’ll have to create another one. Add this to .env also.
OKTA_TOKEN={yourOktaAPIToken}

Create a new file named okta.js. This is where you’ll create some utility functions, as well as get the app initialized for Okta. When authenticated through Okta, your app will authenticate through an access token using JWT. You can use this to determine who a user is. To avoid dealing directly with authentication in your app, a user would sign in on Okta’s servers, then send you a JWT that you can verify.
okta.js
const session = require(‘express-session’)

const OktaJwtVerifier = require(‘@okta/jwt-verifier’)
const verifier = new OktaJwtVerifier({
clientId: process.env.OKTA_CLIENT_ID,
issuer: `${process.env.OKTA_ORG_URL}/oauth2/default`
})

const { Client } = require(‘@okta/okta-sdk-nodejs’)
const client = new Client({
orgUrl: process.env.OKTA_ORG_URL,
token: process.env.OKTA_TOKEN
})

const { ExpressOIDC } = require(‘@okta/oidc-middleware’)
const oidc = new ExpressOIDC({
issuer: `${process.env.OKTA_ORG_URL}/oauth2/default`,
client_id: process.env.OKTA_CLIENT_ID,
client_secret: process.env.OKTA_CLIENT_SECRET,
redirect_uri: `${process.env.HOST_URL}/authorization-code/callback`,
scope: ‘openid profile’
})

const initializeApp = (app) => {
app.use(session({
secret: process.env.APP_SECRET,
resave: true,
saveUninitialized: false
}))
app.use(oidc.router)
app.use(‘/access-token’, oidc.ensureAuthenticated(), async (req, res, next) => {
res.send(req.userContext.tokens.access_token)
})
}

module.exports = { client, verifier, initializeApp }

The initializeApp function adds some middleware to allow you to log in with Okta. Whenever you go to the http://localhost:4000/access-token, it will first check that you’re logged in. If you aren’t, it will first send you to Okta’s servers to authenticate. Once authentication is successful, it returns you to the /access-token route and will print out your current access token, which will be valid for about an hour.
The client that you’re exporting allows you to run some administrative calls on your server. You’ll be using it later to get more information about a user based on their ID.
the verifier is what you use to verify that a JWT is valid, and it gives you some basic information about a user, like their user ID and email address.
Now, in index.js, you’ll need to import this file and call the initializeApp function. You also need to use a tool called dotenv that will read your .env file and add the variables to process.env. At the very top of the file, add the following line:
require(‘dotenv’).config({ path: ‘.env’ })

Just after the app.use(cors()) line, add the following:
const okta = require(‘./okta’)
okta.initializeApp(app)

To make this all work, you’ll also need to install a few new dependencies:
npm i @okta/jwt-verifier@0.0.12 @okta/oidc-middleware@1.0.0 @okta/oidc-sdk-nodejs@1.2.0 dotenv@6.0.0 express-session@1.15.6

You should now be able to go to http://localhost:4000/access-token to log in and get an access token. If you were just at your developer console, you’ll probably find you’re already logged in. You can log out of your developer console to ensure the flow works properly.
Create GraphQL Mutations
Now it’s time to use real data. There may be some real John and Jane Does out there, but chances are they don’t have an account on your application yet. Next, I’ll show you how to add some mutations that will use your current user to create, edit, or delete a post.
To generate IDs for a post, you can use uuid. Install it with npm install uuid@3.3.2, then add it to index.js with:
const uuid = require(‘uuid/v4’)

That should go near the top of the file, next to the other require statements.
While still in index.js, add the following types to your schema:
The post Build a Simple API Service with Express and GraphQL appeared first on SitePoint.

Link: https://www.sitepoint.com/build-a-simple-api-service-with-express-and-graphql/

JavaScript Asynchrony and Async/Await in Selenium WebDriver Tests

Selenium is a wonderful library. It supports all major browsers, has all the features we will probably need, and is currently the de-facto standard in browser tests today, and rightfully so.
(For those that don’t know, browser tests are tests that run a browser, automate the browser to interact with your front-end application, and test it that way.)

Link: https://dzone.com/articles/javascript-asynchrony-and-asyncawait-in-selenium-w?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