Created
April 5, 2022 04:15
-
-
Save sagar-barapatre/95db283749b4b3f5bc173b1fef8be397 to your computer and use it in GitHub Desktop.
Implementation of JWT in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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