This text was initially revealed on the Okta developer weblog. Thanks for supporting the companions who make SitePoint potential.
Securing server-to-server API providers could be tough. OAuth 2.0 is a wonderful method to offload consumer authentication to a different service, however what if there isn’t any consumer to authenticate? On this article, I’ll present you ways you need to use OAuth 2.0 outdoors the context of a consumer, in what’s also called the Client Credentials Stream.
As an alternative of storing and managing API keys on your shoppers (different servers), you should use a third-party service to handle authorization for you. The best way this works is that an API shopper sends a request to an OAuth server asking for an API token. That token is then despatched from the API shopper to your API service alongside with their request. After you have the shopper’s token, you’ll be able to confirm its validity without having to retailer any details about the shopper.
- 1 How the Client Credentials Stream Verification Works
- 2 What’s Okta?
- 3 Create a Primary Node API
- 4 Register with an OAuth 2.0 Supplier for Your Node API
- 5 Secure your Node API
- 6 Check your Secure API
- 7 Register Shoppers on the Fly
- 8 Study Extra About Node and OAuth 2.0 Client Credentials with Okta
How the Client Credentials Stream Verification Works
One strategy to confirm tokens you obtain to your API service is to ahead the token to the OAuth server to ask whether it is legitimate. The draw back to this technique is every API request despatched to your server requires a request despatched to the OAuth server as nicely, which will increase the time it takes so that you can reply to your shopper. An alternate is to make use of one thing referred to as native validation, a technique popularized by JSON Net Tokens (JWT). A JWT incorporates your claims (shopper knowledge) in unencrypted, machine-readable JSON.
When utilizing the native validation sample to validate an API token (JWT), you should 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 sure items of JSON knowledge encoded within the token are what you anticipate them to be
How is that safe? you could be questioning. JWTs include three elements: a header, a payload, and a signature. The header and payload are easy base64 encoded strings, which may simply be decrypted and skim. The signature makes use of an algorithm listed within the header, alongside with a personal key, to create a hash of the header and payload. The hash can’t be recreated with out the personal key, however it may be verified with a public key.
In a method, that is like a driver’s license or a passport. It’s fairly troublesome to forge, however it’s very straightforward for any person to take a look at it and see your identify, date of delivery, and different info. You’ll be able to scan the barcode, check it with a black mild, or search for watermarks to assist confirm its validity.
Whereas comparable in idea, a legitimate JWT would truly be far harder to forge. Somebody with sufficient talent can create a convincing driver’s license, however with out the personal key it might take a trendy pc years to brute drive a legitimate JWT signature. Tokens also needs to have an expiration. Whereas configurable, a strong default is one hour. This implies a shopper would wish to request a new token each 60 minutes if it must make a new request to your API server. That is an additional layer of safety in case your token is compromised. Who is aware of? Perhaps there’s a quantum pc on the market that may recreate the signature inside a couple hours.
Now that you simply perceive the fundamentals of the OAuth 2.0 shopper credentials movement works, let’s construct a Node API that makes use of Client Credentials and Okta.
Briefly, we make id administration simpler, safer, and extra scalable than what you’re used to. Okta is an API service that lets you create, edit, and securely retailer consumer accounts and consumer account knowledge, and join them with a number of purposes. Our API lets you:
Register for a forever-free developer account, and if you’re carried out, come again to study extra about constructing safe APIs in Node!
Create a Primary Node API
As a way to get began, I’ll present you how one can create a primary API in Node. Node retains a listing of dependencies alongside with different metadata in a file referred to as package deal.json.
Assuming you’ve got Node put in already, create a new folder in your API server. You possibly can then use npm to generate a package deal.json for you. The command npm init will immediate you for some info, however you possibly can simply maintain hitting Enter to stay to the defaults.
$ mkdir client-credentials-flow
$ cd client-credentials-flow
$ git init
$ npm init
The quickest approach to get an API server up and operating in Node is through the use of Categorical. You possibly can add Categorical as a dependency with the command npm set up email@example.com –save. This creates a folder referred to as node_modules the place categorical and something it will depend on are downloaded, and your app can then use these. To make improvement go quicker, you may as well add a dev dependency referred to as nodemon, which can restart your server everytime you make code modifications. So as to add a dev-dependency, use the -D flag: npm set up -D firstname.lastname@example.org.
When constructing Node apps, you often need to ignore storing the node_modules folder in your git repo. You are able to do that by including node_modules to your .gitignore file.
echo node_modules >> .gitignore
Package deal managers will even embrace a file (e.g. package-lock.json or yarn.lock) in order that whenever you obtain the node_modules on one other machine (with npm set up or yarn), the identical model will get downloaded. This helps forestall any inconsistencies between servers, and retains you from questioning why one thing works in your machine, however not in manufacturing. Make sure that to commit that file to your git repo as nicely:
$ git add .
$ git commit -m “Adding package files.”
You may also add scripts to your package deal.json folder to run these instructions. Create a begin script with the command node . (the . tells it to run the script listed in your package deal.json as fundamental, which by default is index.js. You’ll additionally need to create a dev script with the command nodemon *.js node .. Command line dependencies, like nodemon, are within the path when operating inside a node script. Now you can run these instructions with npm begin or npm run dev. Your package deal.json file ought to now look one thing like this:
“dev”: “nodemon *.js node .”,
“start”: “node .”,
“test”: “echo “Error: no check specified” && exit 1″
Now for probably the most primary “Hello World” categorical app:
const categorical = require(‘categorical’)
const app = categorical()
app.get(‘/’, (req, res) => res.ship(‘Good day World!’))
const port = course of.env.PORT || 3000
app.pay attention(port, () => console.log(`Listening on port $port`))
That’s it! To start out it, sort npm run dev in a terminal window. You possibly can depart this operating whereas we make modifications, and it’ll routinely restart to mirror new modifications. Now go to http://localhost:3000 in your browser (or on the command line with curl http://localhost:3000) and it is best to see Hiya World! echoed again.
Register with an OAuth 2.0 Supplier for Your Node API
Now to safe the app. That is the place you’ll want to arrange an OAuth 2.0 service. Okta is a cloud-based service that permits builders to simply and securely retailer OAuth 2.0 tokens, consumer accounts, and consumer knowledge, then join them with one or a number of purposes. Okta additionally supplies libraries for a lot of languages, together with Node, to make their API very straightforward for a developer to combine into a large number of apps.
You need to use Okta to shortly and simply arrange server-to-server authentication. Should you don’t have already got an account, join a free Okta Developer account. When you register, you’ll be given a distinctive Okta Org URL (e.g. https://yourOktaDomain) and an e-mail to activate your new account.
You’ll want two elements with a view to make client-to-server authentication work: an authorization server, and a check shopper/software.
Create an Authorization Server
The authorization server is the place shoppers can request a token to make use of in your API server. Contained in the Okta dashboard, click on on the API tab within the header, then choose the Authorization Servers tab. Click on Add Authorization Server, then give your server a helpful identify and outline. The Viewers ought to be an absolute path for the server that can be consuming the tokens.
When you create the authorization server, you’ll need a scope in your shoppers to entry. Click on the Scopes tab and add a scope. You’ll be able to have many of those, which might help outline what elements of the API are getting used, and even who’s utilizing it.
Now that you’ve a scope, you additionally have to specify some guidelines to say who has entry to it. Click on the Entry Insurance policies tab and create a new coverage. For now, simply permit entry to All shoppers. Then click on Add Rule and provides it a identify. Since that is just for shopper credentials, take away the opposite grant varieties for appearing on behalf of a consumer (Authorization Code, Implicit, and Useful resource Proprietor Password) so the one grant sort is Client Credentials. Except for that, simply use the default settings for now.
Again on the Settings tab, pay attention to the Issuer. That is the handle shoppers will use to request a token, and what your API server will use to confirm that these tokens are legitimate.
Create a Check Client
In your Okta dashboard, click on on Purposes within the prime header. Purposes are also called shoppers, so that is the place you possibly can create a check shopper. Click on Add Software and select Service (Machine-to-Machine). The one info it wants is a identify, so you need to use one thing like Check Client. This offers you the credentials on your shopper (on this testing case, that may be you).
Secure your Node API
You now have all of the items of the puzzle to make it so solely authenticated customers get the beloved “Hello World” welcome message, and everyone else will get an error.
Safely Retailer Your Credentials
You’ll need to retailer your credentials safely. A method of doing that is to maintain a file regionally that isn’t saved in git (particularly helpful in case your code is open supply, however nonetheless a good factor to do regardless). This additionally allows you to use the identical code for a number of purposes (e.g. dev and manufacturing environments).
Go forward and create a .env file containing the issuer out of your authorization server and the shopper credentials out of your check software. Be certain that so as to add it to your .gitignore file so it doesn’t get added to your git repo: echo .env >> .gitignore. Your .env file ought to look one thing like this:
A fast means in your code to learn the .env file is with a library referred to as dotenv. You’ll be able to set up it with npm set up dotenv. Then add require(‘dotenv’).config() to the primary line of index.js. You need it to be the very first thing that runs in order that the remainder of your code has entry to these setting variables.
Confirm Client Requests
Okta offers a Node library to assist confirm JSON Net Tokens. When it first sees a request to confirm a token, it can fetch the general public keys Okta by way of your authorization server. It’s going to then maintain on to these keys for an hour by default, although that is configurable. If a token is available in that may’t be verified, it’s going to verify with Okta to see if there are new keys to make use of. If it nonetheless can’t confirm it, the library will throw an error. You’ll be able to set up the package deal with npm set up @email@example.com.
It is advisable to present the package deal with the JWT. It’s as much as you to inform your shoppers the right way to present the token, which could be carried out in a variety of methods. Widespread follow is to make use of the Authorization header in an HTTP(s) request that sometimes appears like Bearer MG9h…NhOq==. Modify your / endpoint to search for the token and confirm it with Okta.
const OktaJwtVerifier = require(‘@okta/jwt-verifier’)
const oktaJwtVerifier = new OktaJwtVerifier(
issuer: course of.env.ISSUER,
app.get(‘/’, async (req, res) =>
const authorization = req.headers
if (!authorization) throw new Error(‘You should ship an Authorization header’)
const [authType, token] = authorization.cut up(‘ ‘)
if (authType !== ‘Bearer’) throw new Error(‘Anticipated a Bearer token’)
res.json( error: error.message )
Attempt going to http://localhost:3000 once more. This time you’ll get an error message because you’re not authenticated.
On this instance, verifyAccessToken sends a request to Okta if it will possibly’t instantly confirm the token. In the event you had a setInterval elsewhere within the code, that code might nonetheless execute whereas ready for Okta’s response.
When verifyAccessToken completes, it’ll throw an error if the token is invalid. Subsequently, if it will get previous that line with out throwing an error, it’s protected to imagine the shopper is verified, and you may ship the “Hello World” message. When you needed extra details about the shopper, you would get the response from the verifier with const jwt = await oktaJwtVerifier.verifyAccessToken(token).
Check your Secure API
You now can see that you simply get an error within the browser with out correct authentication, however I haven’t proven you that you could nonetheless correctly confirm your self. As a way to get a token from the authorization server, you possibly can write a easy Node script. Native Node requests are a bit tedious to work with, so you should use the request-promise library, which can can help you proceed utilizing guarantees and the great async/await syntax. Additionally, you will want btoa, which converts a string into base64.
npm set up firstname.lastname@example.org email@example.com
const request = require(‘request-promise’)
const btoa = require(‘btoa’)
const ISSUER, TEST_CLIENT_ID, TEST_CLIENT_SECRET, DEFAULT_SCOPE = course of.env
const check = async () =>
const token = btoa(`$TEST_CLIENT_ID:$TEST_CLIENT_SECRET`)
const token_type, access_token = await request(
authorization: `Primary $token`,
const response = await request(
authorization: [token_type, access_token].be a part of(‘ ‘),
Now, with your app nonetheless operating on port 3000, run the check with node check.js. It will ship a request to Okta to get a token, then ahead that token to your API server and print the outcomes. It is best to get a good “Hello World” greeting!
Register Shoppers on the Fly
You will have a check shopper, however in the actual world, you may need to let individuals join your API with out making you log into Okta and manually create a Client for them. You additionally in all probability wouldn’t need everyone to share the identical shopper id and secret, in an effort to hold monitor of who’s making what requests, how typically, for instance.
Okta offers an API that permits you to automate all types of duties. A type of is creating new purposes. Okta additionally has a Node library to make it actually easy. On your app to authenticate with Okta, you want an API token. Log in to your dashboard, then choose Tokens from the API dropdown within the header. Click on Create Token and provides it a significant identify. It’s going to then offer you a token this one time – should you lose it you’ll have to create one other one. Go forward and add this to your .env file as TOKEN.
Set up the Okta Node SDK with npm set up @firstname.lastname@example.org. It requires your Group URL, so you must add that to your .env file additionally. Then create a new route in index.js for registering new shoppers.
const okta = require(‘@okta/okta-sdk-nodejs’)
const oktaClient = new okta.Client(
orgUrl: course of.env.ORG_URL,
token: course of.env.TOKEN,
app.get(‘/register/:label’, async (req, res) =>
const software = await oktaClient.createApplication(
const client_id, client_secret = software.credentials.oauthClient
request_token_url: `$course of.env.ISSUER/v1/token`,
res.json( error: error.message )
Now you can go to http://localhost:3000/register/Superior+App+Identify (in your browser is ok) to create a new shopper. The primary time you go there, it ought to offer you a shopper id and secret, and remind you the place to request a token. You’ll be able to substitute the shopper id and secret from earlier than with this new one in .env and re-run check.js to see that this shopper additionally works now.
Should you signal again into your Okta Developer Console, you’ll see that “Awesome App Name” has been added as an Software.
Consider, That is a check… That is solely a check. You probably don’t need to permit anyone to brazenly register for an API key with none sort of verification. This could be a good place to implement some kind of CAPTCHA or require consumer authentication to get the API key. As soon as they’ve the API key, they might then use that of their software with out additional consumer authentication.
Study Extra About Node and OAuth 2.0 Client Credentials with Okta
I hope I’ve proven you that it may be very easy to offer your Node APIs a superb degree of safety. Okta has a lot extra to supply with regard to securing your purposes. In the event you’d wish to learn extra about Node, Okta, and OAuth 2.0 Client Credentials, please take a look at a few of these different assets or browse the remainder of the Okta developer weblog:
As all the time, you possibly can hit us up within the feedback under with suggestions or questions, or on Twitter @oktadev. We sit up for listening to from you!