Skip to content

Instantly share code, notes, and snippets.

@cesarkohl
Created August 23, 2021 16:07
Show Gist options
  • Save cesarkohl/bcba9c518e7e1986416bb05c1ad12d32 to your computer and use it in GitHub Desktop.
Save cesarkohl/bcba9c518e7e1986416bb05c1ad12d32 to your computer and use it in GitHub Desktop.
JWT Node
SECRET=mySecret
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
// Data endpoints
app.get('/', (req, res, next) => {
res.json({ message: "OK!" });
});
app.get('/clients', verifyJWT, (req, res, next) => {
res.json([
{
id: 1,
name: 'Cesar'
}
])
});
// Authentication endpoints
require('dotenv-safe').config();
const jwt = require('jsonwebtoken');
app.post('/login', (req, res, next) => {
if (req.body.user === 'cesar' && req.body.password === 'password') {
const id = 1;
const token = jwt.sign({ id }, process.env.SECRET, {
expiresIn: 300 // 5 min
});
return res.json({ auth: true, token: token });
}
res.status(500).json({ message: 'invalid login' });
})
app.post('/logout', (req, res, next) => {
res.json({ auth: false, token: null });
});
// Authorization endpoints
function verifyJWT(req, res, next) {
const token = req.headers['x-access-token'];
if (!token)
return res.status(401).json({ auth: false, message: 'no token provided' });
jwt.verify(token, process.env.SECRET, (err, decoded) => {
if (err)
return res.status(500).json({ auth: false, message: 'failed to authenticate token' });
req.userId = decoded.id;
next();
})
}
const server = http.createServer(app);
server.listen(3000);
console.log('Listening on :3000');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment