,

Implementing JWT Authentication in NodeJS

Posted by


JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties. In this tutorial, we will go through the process of implementing JWT authentication in a Node.js application.

Step 1: Set up your Node.js project
First, create a new Node.js project by running the following command in your terminal:

npm init -y

Next, install the necessary packages for our project by running the following commands:

npm install express body-parser jsonwebtoken

Step 2: Create a basic Express server
Now, let’s create a basic Express server in a file named server.js.

const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');

const app = express();

app.use(bodyParser.json());

const secretKey = 'secret_key';

app.post('/login', (req, res) => {
  const { username, password } = req.body;

  // Perform authentication logic
  if (username === 'admin' && password === 'password') {
    const token = jwt.sign({ username }, secretKey);
    res.json({ token });
  } else {
    res.status(401).json({ message: 'Invalid username or password' });
  }
});

app.get('/profile', (req, res) => {
  const token = req.headers.authorization.split(' ')[1];

  jwt.verify(token, secretKey, (err, decoded) => {
    if (err) {
      return res.status(401).json({ message: 'Invalid token' });
    }

    res.json({ username: decoded.username });
  });
});

app.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});

In this code snippet, we create an Express server with two routes: /login for generating a JWT token upon successful authentication, and /profile for accessing a protected resource.

Step 3: Test the authentication flow
To test the authentication flow, run the server using the following command:

node server.js

Now, open a new terminal window and send a POST request to the /login endpoint with the following command:

curl -X POST -H "Content-Type: application/json" -d '{"username": "admin", "password": "password"}' http://localhost:3000/login

You should receive a response containing a JWT token. Use this token to access the /profile endpoint by sending a GET request with the following command:

curl -H "Authorization: Bearer <token>" http://localhost:3000/profile

You should receive a response containing the username associated with the token.

Step 4: Adding token expiration
To add token expiration to our JWT authentication, modify the token generation code in the /login endpoint as follows:

const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });

Now, the generated token will expire after 1 hour.

Step 5: Securing routes with JWT authentication
To secure specific routes in your application, you can use middleware to verify the JWT token before allowing access to the route. Modify the /profile route in server.js as follows:

app.get('/profile', verifyToken, (req, res) => {
  jwt.verify(req.token, secretKey, (err, decoded) => {
    if (err) {
      return res.status(401).json({ message: 'Invalid token' });
    }

    res.json({ username: decoded.username });
  });
});

function verifyToken(req, res, next) {
  const bearerHeader = req.headers.authorization;

  if (typeof bearerHeader !== 'undefined') {
    const bearerToken = bearerHeader.split(' ')[1];
    req.token = bearerToken;
    next();
  } else {
    res.status(403).json({ message: 'Forbidden' });
  }
}

Now, the /profile route is secured with the verifyToken middleware, which verifies the JWT token before allowing access to the route.

Conclusion
In this tutorial, we’ve covered the basics of implementing JWT authentication in a Node.js application using Express and the jsonwebtoken package. We’ve created a simple JWT authentication flow, added token expiration, and secured routes with JWT authentication. By following these steps, you can enhance the security of your Node.js applications with JWT authentication.

0 0 votes
Article Rating
30 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@gohit8703
2 months ago

thanku piyush you made my journey possible to project building

@banothutharun2743
2 months ago

wow excellent explaination..thank you brother for this playlist 😊

@ShashankGrade-xk9dc
2 months ago

where we use getUser to verify token

@ShashankGrade-xk9dc
2 months ago

when i replace my token with wrong one the app remain run

@knightcore4062
2 months ago

finally understand sessions cookies and jwt…thank you sirji!!!!🙏🙏🙏🙏

@AmitSingh-nq6bp
2 months ago

I really like his vs code theme , did anyone know the name of it ?

@dhruvsolanki4473
2 months ago

Stateless vs Stateful understood because of you, thanks!

@avfitnes96
2 months ago

Thx sir❤❤

@nithenbains
2 months ago

explaination is top-notch
but appke voice tone like a little child is speaks

@abhayyraz
2 months ago

Too Good

@ar.survivalcraft
2 months ago

Bhaiya jab tokens ko cookies me store kiya ho to react js ke routes ko kaise protect kare based on presence of token in cookie?

@chrisjordan5849
2 months ago

Sir ji ek hi video me pura samjha diya karo na bar bar ja ke dusri video pehle dekho

@NKAnimations-mm2pp
2 months ago

Sir I really like your videos but there are 2 problems which I am facing:

1. Your authentication videos are dependent on URLGeneration videos.

2. If someone face any error in the URL at any point he wont be able to continue until that error gets resolved.

3. Solution : if you could provide the source code then it would be easier for us to resolve our errors.

4. Solution : If you could make such videos which are not dependent on each other then it would be easier for us to understand each concept from the Scratch

@AtharvJoshi-jc7ow
2 months ago

then why the heck IRCTC uses session😂
it loggs you out at the last second of your attempt to book tatkal ticket💩

@mayanksinha1883
2 months ago

nodejsurlshortenerserviceauth.js:8
_id: user._id,
^

TypeError: Cannot read properties of undefined (reading '_id')

@pratyushpragyey7002
2 months ago

if anyone getting an error message in getUser function, i suggest you should use try and catch block instead of directly verifying the jwt token
function getUser(token){

if(!token) return null;

try {

return jwt.verify(token ,secret);

} catch (error) {

return null;

}

}
use this insetad

@pallabdandapat1866
2 months ago

sir getting the below error :

C:UserspallaDownloadsshort-url-nodeshort-url-nodenode_modulesjsonwebtokenverify.js:70

return done(new JsonWebTokenError('jwt malformed'));

^

JsonWebTokenError: jwt malformed

at module.exports [as verify] (C:UserspallaDownloadsshort-url-nodeshort-url-nodenode_modulesjsonwebtokenverify.js:70:17)

at getUser (C:UserspallaDownloadsshort-url-nodeshort-url-nodeserviceauth.js:13:16)

at checkAuth (C:UserspallaDownloadsshort-url-nodeshort-url-nodemiddlewaresauth.js:15:18)

at Layer.handle [as handle_request] (C:UserspallaDownloadsshort-url-nodeshort-url-nodenode_modulesexpresslibrouterlayer.js:95:5)

at trim_prefix (C:UserspallaDownloadsshort-url-nodeshort-url-nodenode_modulesexpresslibrouterindex.js:328:13)

at C:UserspallaDownloadsshort-url-nodeshort-url-nodenode_modulesexpresslibrouterindex.js:286:9

at Function.process_params (C:UserspallaDownloadsshort-url-nodeshort-url-nodenode_modulesexpresslibrouterindex.js:346:12)

at next (C:UserspallaDownloadsshort-url-nodeshort-url-nodenode_modulesexpresslibrouterindex.js:280:10)

at cookieParser (C:UserspallaDownloadsshort-url-nodeshort-url-nodenode_modulescookie-parserindex.js:71:5)

at Layer.handle [as handle_request] (C:UserspallaDownloadsshort-url-nodeshort-url-nodenode_modulesexpresslibrouterlayer.js:95:5)

Node.js v20.6.1

[nodemon] app crashed – waiting for file changes before starting…

@namannema3349
2 months ago

i like the way you explain by giving examples and your explanations are very user friendly

@user-hn4lc1cv3p
2 months ago

someone has its source code

@as_if
2 months ago

4:30 difference between this token and the UID