Protect an API using Auth0 the easy way

I am a fan of Auth0. More for business reasons. They have taken Authentication seriously and made it into a trendy business. Kudos to the team.

It is easy to setup a React web app with Auth0 authentication on the front end. They have some pretty standard boilerplate code which works well for most part. Where they make it a bit more complicated for intermediate developers like me is the protecting an API with the authentication. There is some documentation about registering our API with a scope and a lot of other things. But let us make it simple. If I have just a simple API, the access token we get from Auth0 is good enough for protecting our API. There are two major objectives of protecting our API.

  1. Allow only authenticated users to access the API.
  2. Populate the user object and attach it to the incoming request.

I will show you how this is done with just a few lines of code. For this tutorial, I am assuming that you are working with Node and Express.

Express JWT

Start by adding express-jwt package.

yarn add express-jwt

Express JWT is an Express middleware. If there is a valid JWT (JSON Web Token), it retrieves the user information from JWT and attaches to the incoming request. If there is no valid JWT, it errors out with a 401 Unauthorized response. It does all the heavy lifting for you and makes working with Auth0 quite trivial.

const express = require('express');
const jwt = require('express-jwt');

app = express();
const publicKey = fs.readFileSync('./auth0.pem');
app.use(jwt({ secret: publicKey }));

A little bit of theory. Auth0 does asymmetric encryption using private key / public key and RS256 algorithm. So, our Express API needs to know the public key. In the Auth0 dashboard, this information is available in the Advanced Settings section (down below). Either download the certificate and place it in the project root. Or copy the certificate and paste it into a file. Using fs, we read the contents of the certificate and supply it as a param to the JWT middleware.

Test the API with Postman. For all requests, pass the id_token in the request Header as a Bearer token. Get the id_token from local storage of the web app.

With express-jwt package and three lines of additional code, we have setup Auth0 protection for our API.

Related Posts

Leave a Reply

Your email address will not be published.