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.
thanku piyush you made my journey possible to project building
wow excellent explaination..thank you brother for this playlist 😊
where we use getUser to verify token
when i replace my token with wrong one the app remain run
finally understand sessions cookies and jwt…thank you sirji!!!!🙏🙏🙏🙏
I really like his vs code theme , did anyone know the name of it ?
Stateless vs Stateful understood because of you, thanks!
Thx sir❤❤
explaination is top-notch
but appke voice tone like a little child is speaks
Too Good
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?
Sir ji ek hi video me pura samjha diya karo na bar bar ja ke dusri video pehle dekho
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
then why the heck IRCTC uses session😂
it loggs you out at the last second of your attempt to book tatkal ticket💩
nodejsurlshortenerserviceauth.js:8
_id: user._id,
^
TypeError: Cannot read properties of undefined (reading '_id')
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
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…
i like the way you explain by giving examples and your explanations are very user friendly
someone has its source code
4:30 difference between this token and the UID