Protect express API routes with Auth0

protect your private express API routes using jwt and jwks

Fri, 02 Nov 2018

Sometimes you may want to add protected routes to your application either to make sure certain information is only accessible to people of a certain role or to make a route only accessible for people who are authenticated.

Setup

Install the required dependencies

npm install express-jwt jwks-rsa

yarn add express-jwt jwks-rsa

Auth0 API

  1. Sign into you’re Auth0 account
  2. Click APIs on the side menu
  3. Click Create API located at the top right
  4. Chose RS256 as the signing algorithm
  5. Copy the Identifier field located under Settings

Express Backend

Next up is to add your jwtCheck. After initiate your express object add the following code

var jwtCheck = jwt({
  secret: jwks.expressJwtSecret({cache: true, rateLimit: true, jwksRequestsPerMinute: 5, jwksUri: "https://yourAuthDomain.auth0.com/.well-known/jwks.json"}),
  audience: '**Paste your indentifier here**',
  issuer: "https://yourAuthDomain.auth0.com/",
  algorithms: ['RS256']
});

Block Private Routes

You can block routes with one of two methods

  1. Require all routes to be private. This method is the easiest way to block routes if you just want no one without a login to be able to access your API routes. After you create your jwtCheck, just include it in your express object

    var app = express();
    app.use(jwtCheck);
  2. If you want to block certain paths you can just add the jwtCheck to the route itself.

    router.get('/', jwtCheck, function(req, res) {
    res.json({message: 'API Initialized!'});
    });

Pass Client Token

Once you add the jwtCheck to your backend, all API request made without a proper token will be denied. In your auth file you want to add the following function which will return the users Auth0 token

  getAccessToken() {
    const accessToken = localStorage.getItem('access_token');
    if (!accessToken) {
      throw new Error('No access token found');
    }
    return accessToken;
  }

Next up is to add this function to our Auth0 constructor

  constructor() {
    this.getAccessToken = this.getAccessToken.bind(this);
  }

This part may be different depending on how you set up your Auth0 object. You want to add the token to the header of your API request. If you were using axios, the API call would look something like this.

      const headers = {
        'Authorization': `Bearer ${this.props.auth.getAccessToken()}`
      }
		axios.get(`${apiURL}/`, {headers})
Buy Me A CoffeeDigitalOcean Referral Badge
Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge