Skip to content

Instantly share code, notes, and snippets.

@kdby-io
Created July 23, 2017 10:26
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 kdby-io/a5d57392387befdc0a79848b9e060c12 to your computer and use it in GitHub Desktop.
Save kdby-io/a5d57392387befdc0a79848b9e060c12 to your computer and use it in GitHub Desktop.
[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