Skip to content

Instantly share code, notes, and snippets.

@sagar-barapatre
Created April 5, 2022 04:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagar-barapatre/95db283749b4b3f5bc173b1fef8be397 to your computer and use it in GitHub Desktop.
Save sagar-barapatre/95db283749b4b3f5bc173b1fef8be397 to your computer and use it in GitHub Desktop.
Implementation of JWT in Node.js
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.get('/api',(req,res) =>{
res.json({
message:'Welcome to the API'
})
})
app.post('/api/posts',verifyToken,(req,res) =>{
jwt.verify(req.token,'secretkey',(err,authData) =>{
if(err){
res.sendStatus(403)
} else{
res.json({
message:'Post successfully created',
authData:authData.user
})}})})
app.post('/api/login',(req,res) =>{
const user ={
id : 2,
username: 'Sagar',
email: 'test@gmail.com'
}
jwt.sign({user:user},'secretkey',(err,token) =>{
res.json({
token:token
})
})
})
function verifyToken(req,res,next)
{
const bearerHeader = req.headers['authorization'];
if(typeof bearerHeader !== 'undefined')
{
const bearer = bearerHeader.split(' ');
const bearerToken = bearer[1];
req.token = bearerToken;
next();
}else{
res.sendStatus(403);
}
}
app.listen(5000,() => console.log('Server started on Port 5000'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment