token的用处
其他请求数据的时候需要携带该token,如果token验证失败或已过期,将拿不到数据
使用
router.get('/current',"验证token", (res, req) => {})
工具 passport-jwt passport
注意:passpport 需要在server.js中初始化并添加配置项
1 2 3
| const passport = require('passport'); app.use(passport.initialize()); require('./config/passport')(passport);
|
配置信息passport.js文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| const passportJwt = require('passport-jwt'); const JwtStrategy = passportJwt.Strategy; const ExtractJwt = passportJwt.ExtractJwt; const mongoose = require('mongoose'); const User = require('../models/User'); let opts = {}; opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken(); opts.secretOrKey = 'secret';
module.exports = passport => { passport.use(new JwtStrategy(opts, (jwt_payload, done) => { console.log(jwt_payload,'jwt_payload') User.findById(jwt_payload.id) .then(user => { if (user) { return done(null, user); } else { return done(null, false) } }) .catch(err => console.log(err)) })); }
|
接口测试验证token user.js
1 2 3 4 5 6 7
| router.get('/current',passport.authenticate("jwt", {session: false}), (req, res) => { res.json({ id:req.user.id, name: req.user.name, email: req.user.email }); })
|