NodeJS is now one of the most widely used back-end JavaScript environment in creating Rest APIs for applications, it is continuously growing as more developers create and develop libraries on npm allowing NodeJS development easier for third party integration.
Speaking about third party integration, in this article we will tackle about how to integrate and secure our NodeJS endpoints with Auth0 JWT in just simple steps. we will apply JWT authentication that will create tokens used for validations on our created Auth0 API,
Prerequisites
Setting up Auth0 API
The first thing we need to do is we need to create our Auth0 API that will secure our endpoint, I assume here that you have already created your Auth0 account.
on the Auth0 dashboard, go the API Menu and we will create our new API.
in this example we will name our API as Node JS API, our identifier must be a URL but this is not required to be deployed, for the signing algorithm we will be using RS256.
After successful creation of our API, we will now see our new API on the list, by opening our API we will see the settings and other information we need for our NodeJS connection.
on the Machine to Machine Applications, we will see that a test application is automatically created on our API, this is the application we will connect on our NodeJS that we will be developing later. we will be needing the domain, client and client secret information for our connection.
Setting up NodeJs
Now that we have successfully created our Auth0 API, we will now create our NodeJS application, lets create our new folder named node-js-auth0 or any project name you prefer, and inside the folder we will execute the following command.
npm init -y
this will initialize our directory as a node project and it will generate a package.json that will hold our dependencies details for our application.
now we will install our needed dependencies to implement our Auth0. execute the following command to install our dependencies.
npm install express express-jwt express-jwt-authz jwks-rsa
express - is a framework that we will use with NodeJS to create our API endpoints
express-jwt - a middleware for validating JWT in the jsonwebtoken module
Jwks - a set of public keys that enables clients to validate JSON web tokens that is issued by an OpenID connect provider.
express-jwt-authz - will be used for validation of access base on scopes that an application has.
Now we have successfully installed our dependencies, we will create our NodeJS entry point, in the of our project folder, we will create an index.js file where we will establish our connection, in the index.js file we will place the ff. code.
const express = require('express');
const app = express();
const jwt = require('express-jwt');
const jwks = require('jwks-rsa');
app.use(jwt({
secret: jwks.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 25,
jwksUri: 'https://dev-ew42azyb.us.auth0.com/.well-known/jwks.json'
}),
audience: 'https://node-js-api.com',
issuer: 'https://dev-ew42azyb.us.auth0.com/',
algorithms: ['RS256']
}));
app.listen(3000);
we can see above that we have used the domain of our generated Auth0 API in the issuer and jwksUri, we have just added /.well-known/jwks.json on the jwkUri property, we hace also used identifier in the audience property.
we have listen to port 3000 where we will run our application, now our next step is to add a simple endpoint in our application, place the following code to create an /authtest endpoint.
app.get('/authtest', (req, res) => {
res.json({ loggedin: true });
});
now we have created our a example endpoint and we will run our application by executing npm run start.
In our postman let's call our created /auth/test endpoint, we will expect on this part that it will return the {loggedin: true} object but rather it will return an error.
don't worry this is a good sign that our Auth0 integration is already working as our endpoints are now secured with Auth0 JWT, we can see on our request that we have not included a token on our header, to generate an example valid token, we will call the domain of our Auth0 API with oauth/token on the path and we will use the client_id, client_secret and audience information in the request body.
we can see above that the response has now a valid JWT that we can use to request on our created endpoint, we will place the generated token on the request header using Authorization key and try to call our endpoint again.
We can now see on our request is now successful as it returned the {isLoggedin: true} object in the response body.
we have successfully integrated our Auth0 on our NodeJS API! but now we will try to implement scope permission on our endpoint using express-jwt-authz.
Scope Permissions
in Auth0 we can also control what endpoints can be accessed on a specific application by the use of Scopes. We will be using express-jwt-authz to check if the application requesting has a valid scope.
In our index.js of our NodeJS app, we will add the following code.
const jwtAuthz = require('express-jwt-authz');
const checkScopes = permissions => jwtAuthz(permissions);
Now we will create two endpoints with a checkScope middleware that will check if the scope of the requesting application is valid.
app.get('/blogs', checkScopes(['read:blog']), (req, res) => {
res.json({ readBlogAccess: true });
});
app.post('/blogs', checkScopes(['create:blog']), (req, res) => {
res.json({ createBlogAccess: true });
});
the first endpoint allows applications that has a read:blog scope only on the other hand, the second endpoint allows create:blog only scope.
now if we try to access this endpoints even we have a valid token on our headers, this would not allow us to access the URL having that our test application has no valid scopes.
we can see on our Postman request that it has returned an insufficient scope on the response.
To add a scope on our test application, lets go back on our Auth0 menu and select our created API, on the permissions tab we will create two permissions named read:blog and create:blog.
we can see on our list that our permissions has been added successfully, we can now add this permission on our test application we are using, go to Machine to Machine Applications tab and click the caret beside the test application, we will add the two created permissions by ticking the checkbox.
now after updated our Test application we will try to request again on our Postman if our application has now access.
and now our request to the /blogs endpoint is now successful as our application has a valid scope defined.
We have now successfully integrated Auth0 security on our NodeJS endpoints with scope and permissions, for the example code for this project, this is the GitHub repository link https://github.com/SeijiV13/nodejs-auth0-security
for more tutorials, you can check out my other contents in this blog, I hope you learned and enjoyed this content cheers!
Comments