Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

passport-jwt #141

Open
uniquejava opened this issue Sep 27, 2017 · 0 comments
Open

passport-jwt #141

uniquejava opened this issue Sep 27, 2017 · 0 comments

Comments

@uniquejava
Copy link
Owner

uniquejava commented Sep 27, 2017

关于jwt, 见: #106
关于passport-local见#126
关于curl见: #107

passport-jwt是最没必要使用的一个中间件, 直接使用jsonwebtoken 或者使用passport-local + jsonwebtoken实现即清楚又简单.

这里是一篇单用jsonwebtoken的教程: https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

折腾的笔记, 备份.

passport-jwt定义

关于passport-jwt, 官方定义如下:

A Passport strategy for authenticating with a JSON Web Token.

This module lets you authenticate endpoints using a JSON web token. It is intended to be used to secure RESTful endpoints without sessions.

npm install passport-jwt --save

用法

生成Token: indexRoutes.js

router.post('/login', function (req, res, next) {

  var username = req.body.username;
  var password = req.body.password;

  Users.findOne({username: username, password: tools.encrypt(password)})
    .then(function (user) {
      if (!user) {
        return res.sendStatus(401);
      }

      var myToken = jwt.sign({user: user.id},
        config.jwt.secret,
        {expiresIn: config.jwt.expiresIn});

      res.json({token: myToken});

    })
    .catch(function (err) {
      res.status(400);
      res.json({result: 'error', message: err});
    });

});

定义Strategy: passport.jwt.js

var passport = require('passport');
var config = require('../config/config');
var jwt = require('jsonwebtoken');

var passportJWT = require("passport-jwt");
var ExtractJwt = passportJWT.ExtractJwt;
var JwtStrategy = passportJWT.Strategy;


var jwtOptions = {};
// 兼容2.x的方式: ExtractJwt.fromAuthHeaderWithScheme('jwt');, 定义了Authorization前面的type为JWT(不区分大小写)
// 兼容OAuth2的方式: ExtractJwt.fromAuthHeaderWithScheme('bearer'); 定义type为Bearer(不区分大小写) 和 下面的写法效果一样.
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();

jwtOptions.secretOrKey = config.jwt.secret;

var strategy = new JwtStrategy(jwtOptions, function (jwt_payload, next) {
  console.log('JwtStrategy is called.');
  console.log('jwt_payload: ', jwt_payload);
  if (jwt_payload) {
    next(null, jwt_payload);
  } else {
    next(null, false);
  }
});

passport.use('jwt', strategy);

module.exports = passport;

使用Strategy: server-app.js

// passport config
require('./config/passport.jwt');

app.use(passport.initialize());

app.use('/', require('./routes/indexRoutes'));
app.use('/api/v1', passport.authenticate('jwt', { session: false }), require('./routes/apiRoutes'));

解释说明

POST /login的时候和passport-local不同, 不需要passport参与 直接取username/password经DB验证成功则响应token, 否则响应401

请求API的时候, passport-jwt参与取request header中的Authorization信息, 解密成功则next(null, jwt)将请求交给实际的API调用方法, 解密失败则done(null, false), 直接响应401给client.

passport-jwt和passport-local用法上的区别

passport-jwt: a. 在POST /login时生成token b. 在GET /api/v1时使用strategy验证请求中的token是否有效.

passport-local: a.在POST /login时使用strategy验证请求中的user/pass是否有效(有效则调用serializeUser, 还有自定义的callback. b.在GET /api/v1时调用deserializeUser, 通过req.isAuthenticated()判断用户是否登录.

passport-local中的callback:

router.post('/login', passport.authenticate('local', {
  failureRedirect: '/login',
  failureFlash: true 
}), function (req, res) {
  var user = req.user;
  console.log(user + ' logged in.');
  req.session.user = user;
  res.cookie('token', someToken);
  res.redirect(user === 'admin' ? '/admin' : '/xxxx');
});

另一种更简单的方式是使用: https://github.com/auth0/express-jwt

passport-jwt 2.x和3.x的区别

If you want to maintain the behavior of ExtractJwt.fromAuthHeader() when switching to v3.3.0, simply replace it with ExtractJwt.fromAuthHeaderWithScheme('jwt') in your implementation.

References

  1. https://github.com/themikenicholson/passport-jwt
  2. Refactoring a Basic, Authenticated API with Node, Express, and Mongo
  3. Express, Passport and JSON Web Token (jwt) Authentication for Beginners
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant