Hi there! I'm Bryan Lor, an application developer from Minnesota, and this is my site where I share things about coding, app development, and things I've been working on. To know more, go to the "About" page below!

Search form

Main menu

Securing your API using Auth0 and Lock

Introduction

You don't necessarily have to be using the same things that I use on my project to follow along. Use this as a general guideline to provide you with ideas on how to approach it.

I am not going to list every single library, package, etc. that I'm using on my project. I'll list the ones that are important.

The front-end client uses the following tech:

Auth0, specifically their Lock widget

React

whatwg-fetch package

The API uses the following:

NodeJS

ExpressJS

jsonwebtoken package

express-bearer-token package

What this will NOT cover:

Getting Auth0 implemented with React

How to build a React app

How to build an API

This is only to help others who have already implemented Auth0 and have an API that their client is talking to that needs to be secured, but would like ideas on how to go about it.

Setup a non interactive client in Auth0

1.) Go to Auth0 and click on "Clients" in the left navigation (A) then "Create Client" (B):

2.) Then enter a name for your non interactive client, make sure to select "Non Interactive Clients", and click "Create":

3.) Follow the instructions that Auth0 provides you in how to set up the rest of the non interactive client.

The non interactive client will be used for providing us the access token. I've tried it where the main client tries to provide the access token, but it doesn't work...at least not for me.

Retrieving the access token while using Auth0's Lock widget

You must have already implemented Auth0's Lock widget into your React app. I used the following documentation to implement the Lock widget: https://auth0.com/docs/quickstart/spa/react/01-login. This section will assume that you followed the documentation and have a class called AuthService.

In your AuthService class (AuthService.js), we're going to create a method like the following:

In the above code, I am using fetch() which comes from the package, whatwg-fetch, so make sure you have that downloaded. This lets me call the oauth URL that can be found in Auth0 at Clients ---> Your non interactive client ---> Advanced Settings ---> Endpoints:

We're going to retrieve the access token as we're logging in using the Lock widget. This method would be called along the way during the login process. I called it after I have set the id token.

Check out the below process diagram to have a better visualization of how the process works:

Sending the access token to the API

After you have retrieved the access token, you want to send it as a Bearer token to your API as a part of the Authorization header. Below is a code snippet of how I sent it in my code. You'll want to do something similar.

static createExpenseCard(userId){

return fetch('http://localhost:3001/api/expense-card', {

method:'POST',

headers:{

'Content-Type':'application/json',

'Authorization':'Bearer '+ localStorage.getItem('access_token'),

},

body: JSON.stringify({

userId: userId,

}),

})

.then(this.checkStatus)

.then(function(response){

return response.json();

});

}

Checking the access token over at the API

Over on the server side, you want to check to make sure that the access token is valid. The way I did this was using the following packages: jsonwebtoken, express-bearer-token, fs. Below is the code snippet that is used, albeit still incomplete:

res.status(403).json('Unable to use the API without valid credentials.');

validAuthorization =false;

break;

case'JsonWebTokenError':

res.status(403).json('Unable to use the API without valid tokens.');

validAuthorization =false;

break;

default:

res.status(500).json('Error occurred trying to get to the API.');

validAuthorization =false;

}

}

// Test for decoded values and throw errors.

console.log(decoded);

// If everything is valid, proceed onwards.

if(validAuthorization){

next();

}

});

});

You'll find plenty of tutorials out there that show you how to check for a valid access token if you're not using the same packages as me. Maybe you already wrote your code to check this!

After the access token is checked and is good, then we continue with our business like usual. I didn't make it too difficult right now with scopes since every user has the same permissions, but maybe in the future if I do, the server side code will definitely be more than just a check on the validity of the access token.