Token Based Authentication Made Easy | jwt api authentication
JWTAuthenticationwithAuth0We will needtomakesomeslightmodificationstoour codetoshowcasetheauthenticationflowwithAuth0.Let’sexaminethechangesbelow://Loadinourdependenciesvarexpress=require(express);varjwt=require(express-jwt);varjwtCheck=jwt({secret:newBuffer({YOUR-APP-SECRET},base64),audience:{YOUR-APP-CLIENT-ID}});varapp=express();//Ratherthancheckingforatokenwithinourcontroller//welluseamiddlewaresoifthetokenisinvalidwell//stopfurtherexecutionoftherequestapp.use(/api,jwtCheck);app.get(/,fu...
JWT Authentication with Auth0We will need to make some slight modifications to our code to showcase the authentication flow with Auth0. Let’s examine the changes below:
// Load in our dependencies var express = require(express); var jwt = require(express-jwt); var jwtCheck = jwt({ secret: new Buffer({YOUR-APP-SECRET}, base64), audience: {YOUR-APP-CLIENT-ID} }); var app = express(); // Rather than checking for a token within our controller // well use a middleware so if the token is invalid well // stop further execution of the request app.use(/api, jwtCheck); app.get(/, function(req, res){ res.send("Welcome to our API"); }) app.get(/api, function(req, res){ var secrets = {"accountNumber" : "938291239","pin" : "11289","account" : "Finance"}; res.json(secrets); }) app.listen(3000);To test that this works, let’s start the server and navigate to localhost:3000/api. We see a message saying that we didn’t send an authorization token. Let’s head...