Unlock Expert Advice with Zero Commitment.
We’ve Eliminated the Barriers.
API security is very important and emerging as a concern than ever before. Here, learn how to implement user identity management and authorization with JSON Web Tokens.
Have you ever noticed how authentication works? What is behind all the abstractions and complexity? It’s nothing special actually. Encrypting a value, it is a way, in turn, creating unique token users use as an identifier. The token verifies user’s identity and can authenticate who you are and approve various resources you have access to.
What does JWT actually mean in a down to earth point of view? Let’s break down what the official definition states:
What does JSON Web Token actually mean in the official definition? Let’s get it straight.
“JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.”
– Internet Engineering Task Force (IETF)
When a user successfully logs in using their credentials during the authentication process, a JSON Web Token is returned and must be saved locally in local storage. Whenever the user wants to access a protected resource or route, the JWT must be sent to the user agent usually in the Authorization header Bearer Schema with the request.
Next, when a back-end server receives a JWT with a request, the first things to do is to validate the token. The following list consists of a series of steps. If any of these fails then the request must be rejected.
• Check that the JWT is well-formed
• Check the signature
• Validate the standard claims
• Check the Client permissions (scopes)
There are some things you must know before we start explaining about Node.js and some ECMAScript standards. As we will expect you already know how to build a RESTful API using Node.JS. This blog will not get into the nitty-gritty details but these resources can provide more information about JWTS and its validation.
All things considered, not yet actually. We have to set up the environment first. The code should hold up no less than a couple more minutes. This part is exhausting so to get up and running fast we’ll clone the repository from the instructional tutorial above. Open up a terminal window or run this command:
git clone https://github.com/adnanrahic/nodejs-restful-api.git
You’ll find a folder, just open it up. Take a look at the folder structure.
> user - User.js - UserController.js - db.js - server.js - app.js - package.json
We have a client folder with a model and a controller, and fundamental CRUD effectively executed. Our app.js contains the essential arrangement. The db.js ensures the application interfaces with the database. The server.js ensures our server spins up.
Simply ahead and introduce all required Node modules. Switch back to your terminal window. Ensure you’re in the envelope named ‘nodejs-restful-api’ and run npm install. Sit tight for a moment or two for the modules to introduce. Presently you have to include a database association string in db.js.
Now, you can spin up the server back in your terminal window type node server.js.
Go ahead and spin up the server, back in your terminal window type node server.js. You should see Express server listening on port 3000 get logged to the terminal.
We should begin by conceptualizing about what we need to build. Most importantly we need to include client validation. It Signifies, executing a framework for enrolling and logging users in.
Also, we need to include approval. The demonstration is of allowing clients the authorization to get to specific assets on our REST API.
Begin by including another record in the root directory of the project. Give it a name of config.js. Here you’ll put arrangement settings for the application. All that we require right now is simply to characterize a mystery key for our JSON Web Token.
// config.js module.exports = { 'secret': 'supersecret' };
With this additional, you’re prepared to start including the authentication. Make an envelope named auth and begin by including a document named AuthController.js. This controller will be home for our authentication logic.
Add this bit of code to the highest point of the AuthController.js.
// AuthController.jsvar express = require('express'); var router = express.Router(); var bodyParser = require('body-parser'); router.use(bodyParser.urlencoded({ extended: false })); router.use(bodyParser.json()); var User = require('../user/User');
Now your system is all ready to put in the module for utilizing JSON Web Tokens and encrypting passwords. Use this code into the AuthController.js:
var jwt = require('jsonwebtoken'); var bcrypt = require('bcryptjs'); var config = require('../config');
You must open up a terminal window in your project folder. Now install the following modules:
npm install jsonwebtoken --save npm install bcryptjs --save
You are ready to create or register endpoint. Insert this code to your AuthController.js:
router.post('/register', function(req, res) { var hashedPassword = bcrypt.hashSync(req.body.password, 8); User.create({ name : req.body.name, email : req.body.email, password : hashedPassword }, function (err, user) { if (err) return res.status(500).send("There was a problem registering the user.") // create a token var token = jwt.sign({ id: user._id }, config.secret, { expiresIn: 86400 // expires in 24 hours }); res.status(200).send({ auth: true, token: token }); }); }); res.status(200).send({ auth: true, token: token }); }); });
Here we’re anticipating that the client should send us three values, a name, an email and a password. We’re instantly going to take the secret key and encode it with Bcrypt’s hashing method. At that point take the hashed password, incorporate name and email and make new user. After the user has been effectively made, we’re calm to make a token for that user.
The jwt.sign() technique takes a payload and the secret key characterized in config.js as parameters. It makes an exceptional series of characters speaking to the payload. For our situation, the payload is a protest containing just the id of the client. We should compose a bit of code to get the client id in view of the token we got once again from the enroll endpoint.
router.get('/me', function(req, res) { var token = req.headers['x-access-token']; if (!token) return res.status(401).send({ auth: false, message: 'No token provided.' }); jwt.verify(token, config.secret, function(err, decoded) { if (err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' }); res.status(200).send(decoded); }); });
Here we’re expecting the token to be sent alongside the request in the headers. The default name for a token in the headers of a HTTP ask for is x-access-token. If there is no token gave the demand the server sends back an error. To be more exact, a 401 unapproved status with a reaction message of ‘No token gave’. If the token exists, the jwt.verify() strategy will be called. This technique unravels the token making it conceivable to see the first payload. We’ll deal with blunders if there are any and if there are not, send back the decoded an incentive as the response.
At long last we have to add the course to the AuthController.js in our primary app.js document. To start with send out the switch from AuthController.js:
// add this to the bottom of AuthController.js module.exports = router;
Where you exported the app, add areference to the controller in the main app.
// app.js var AuthController = require('./auth/AuthController'); app.use('/api/auth', AuthController); module.exports = app;
As we are covering up how to secure a RESTful API, we are hoping to cover them up in near future. It’s fine to take a back step and rest for a while before trying again. Unified Infotech is a promising Website Development Company in NYC giving world-class solutions to every problem. Have fun and be innovative!
We’ve Eliminated the Barriers.
We stand by our work, and you will too.