Skip to content

Instantly share code, notes, and snippets.

@ArVan
Last active March 11, 2021 03:06
Show Gist options
  • Save ArVan/a8eb2bff9e453a1850d17dd3af1d0bea to your computer and use it in GitHub Desktop.
Save ArVan/a8eb2bff9e453a1850d17dd3af1d0bea to your computer and use it in GitHub Desktop.
JWT Authentication with Passport
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var user = require('./routes/user');
var auth = require('./routes/auth');
const passport = require('passport');
require('./passport');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/user', passport.authenticate('jwt', {session: false}), user);
app.use('/auth', auth);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const passport = require('passport');
/* POST login. */
router.post('/login', function (req, res, next) {
passport.authenticate('local', {session: false}, (err, user, info) => {
console.log(err);
if (err || !user) {
return res.status(400).json({
message: info ? info.message : 'Login failed',
user : user
});
}
req.login(user, {session: false}, (err) => {
if (err) {
res.send(err);
}
const token = jwt.sign(user 'your_jwt_secret');
return res.json({user, token});
});
})
(req, res);
});
module.exports = router;
const passport = require('passport');
const passportJWT = require("passport-jwt");
const ExtractJWT = passportJWT.ExtractJwt;
const LocalStrategy = require('passport-local').Strategy;
const JWTStrategy = passportJWT.Strategy;
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function (email, password, cb) {
//Assume there is a DB module pproviding a global UserModel
return UserModel.findOne({email, password})
.then(user => {
if (!user) {
return cb(null, false, {message: 'Incorrect email or password.'});
}
return cb(null, user, {
message: 'Logged In Successfully'
});
})
.catch(err => {
return cb(err);
});
}
));
passport.use(new JWTStrategy({
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey : 'your_jwt_secret'
},
function (jwtPayload, cb) {
//find the user in db if needed
return UserModel.findOneById(jwtPayload.id)
.then(user => {
return cb(null, user);
})
.catch(err => {
return cb(err);
});
}
));
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
/* GET user profile. */
router.get('/profile', function(req, res, next) {
res.send(req.user);
});
module.exports = router;
@oanh-JL
Copy link

oanh-JL commented Mar 4, 2019

which port for app run ???

@r2dev
Copy link

r2dev commented Mar 16, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment