In this article, we are going to cover how to access the JSON web token (jwt) and also to protect our routes by the JSON web token.
Have you ever thought about the process of authentication? What lies under the layers of abstraction and complexity? Nothing out of the ordinary. It's a method of encrypting data and generating a one-of-a-kind token that users can use to identify themselves. Your identity is verified with this token. It will verify your identity and grant you access to a variety of services. If you don't recognize any of these words, don't worry, I'll explain everything below.
Before we get started into this we should have few things installed in our machine.
Create a new folder with project name (NodeAuthAPI) and open the same folder in Visual Studio Code (VS Code)
Run the following command to initialize our package.json file.
Install all our remaining dependencies
- npm install express jsonwebtoken
Why these Dependencies?
express - running on the server (Port number)
jsonwebtoken - This will be used to sign and verify Json web tokens.
nodemon - will use this to restart our server automatically whenever we make changes to our files.
Create a file named index.js inside the project.
Project Structure
Let's import the packages in index.js file
- const express = require("express");
- const jwt = require("jsonwebtoken");
Now initialize the app variable with express
setup the port number for our server to process
- app.listen(5000,()=>console.log('listening on port 5000'));
Let's run and test whether our app is running under the same port number which we mentioned above.
Run the command in the terminal - nodemon to check the output
Create a simple get method to check the output in Postman.
index.js
- app.get('/api',(req, res) => {
- res.json({
- message: 'Welcome to the API!',
- });
- });
Postman
So it is confirmed that our get method is working as expected, Now configure the jwt setup to check with the actual authentication mechanism. Create a post API Login Method with Mock username and Email and also i have setup the token expiration seconds in the same method.
- app.post('/api/Login',(req, res) => {
-
- const user ={
- username: 'jk',
- email: '[email protected]'
- }
- jwt.sign({user:user},'secretkey',{expiresIn: '30s'},(err,token)=>{
- res.json({token})
- })
- })
Postman
The token is generated with basic credentials, Now we need to validate another API with this token to access the credentials.
Create a function and verify the token which will be passed as a header
Sample Authorization : Bearer <your token>
-
-
-
-
- function verifyToken(req, res,next) {
-
- const bearerHearder = req.headers['authorization'];
-
- if(typeof bearerHearder != 'undefined'){
-
- const bearer = bearerHearder.split(' ');
-
- const bearerToken = bearer[1];
-
- req.token = bearerToken;
-
- next();
-
- }else{
-
- res.sendStatus(403);
- }
- }
Let's create an API to validate this token
-
- app.post('/api/validate',verifyToken,(req, res)=>{
- jwt.verify(req.token,'secretkey',(err,authData)=>{
- if(err){
- res.sendStatus(403);
- }else{
- res.json({
- message: 'Validated',
- authData
- });
- }
- });
- });
Testing with Postman
If you are trying to access the validate API without passing the token it will give us 403 Forbidden because of unauthorized access.
Now let's get the token first by accessing the Login API and then pass the same token as the header in the Validate API to get the access and as well as result.
Note
After 30 sec the token will expire because we defined the expiration time in code, we need to get the token again by accessing the login API
Thanks for reading this article, Hope you got a clear picture in understanding this Node.js API Authentication with jwt.
...Keep learning !!!