Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[blog] /2017-jwt-authentication-on-expressjs
const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const jwt = require('jsonwebtoken');
const SECRET = 'SECRET';
/*
* Database
*/
const user = {
id: 1,
username: 'test',
password: '123'
};
/*
* Server
*/
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
/*
* Setup for JWT authentication
*/
passport.use(new JwtStrategy({
jwtFromRequest: ExtractJwt.fromAuthHeader(),
secretOrKey: SECRET
}, (payload, next) => {
if (payload.id !== user.id) {
next(null, false);
} else {
next(null, user);
}
}));
app.use(passport.initialize());
/*
* Routes
*/
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username !== user.username || password !== user.password) {
return res.status(401).end(); // login failed
}
const token = jwt.sign({ id: user.id, username: user.username }, SECRET, { expiresIn: '1d' });
return res.json({ accessToken: token });
});
app.put('/users/:userId', passport.authenticate('jwt', { session: false }), (req, res) => {
// Authorization
if (req.params.userId != req.user.id) {
return res.status(403).end();
}
const newPassword = req.body.password;
user.password = newPassword;
return res.status(200).json({ result: 'success' });
});
const port = 3000;
app.listen(port, () => {
console.log(('App is running at http://localhost:%d'), port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment