Skip to content

Instantly share code, notes, and snippets.

@ljahier
Created June 18, 2020 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ljahier/4b93e3a9eb2860ab724fa3204c069dbc to your computer and use it in GitHub Desktop.
Save ljahier/4b93e3a9eb2860ab724fa3204c069dbc to your computer and use it in GitHub Desktop.
NodeJS Auth with JWT
const express = require('express');
const app = express();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken')
require('dotenv').config();
const user = {
id: 1,
email: 'public@example.com',
password: '$2b$10$YjiNp8gnJRqTQ5o8epBwFuX9fE3usawPkEZ0ZknnVs5YeSy53eW6e',
role: ['Admin']
};
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.json({ 'data': 'API root' });
})
app.post('/login', (req, res) => {
let bcryptRes = bcrypt.compareSync(req.body['password'], user.password);
if (bcryptRes === true) {
res.status(200).json({ token: jwt.sign({ user }, process.env.ACCESS_TOKEN_SECRET) });
} else {
res.status(400).send('Username or password are wrong');
}
})
app.get('/protected', authVerif, (req, res) => {
jwt.verify(req.token, process.env.ACCESS_TOKEN_SECRET, (err, data) => {
if (err) res.sendStatus(403);
else res.json({ text: 'this is protected', data: data });
});
})
function authVerif(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(3000, () => console.log('Server running on localhost:3000'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment