首先設(shè)置下載庫文件
yarn add passport-jwt passport jsonwebtoken
jsonwebtoken設(shè)置token
const rule = {id: data._id, name: data.user} // 加密規(guī)則
let token = jwt.sign(rule, 'secret', {expiresIn: 60 * 60}, (err, token) => {
if (err) throw err
// 這里直接返回token
return res.json({code: 0, msg: '用戶登錄成功', token: "Bearer " + token})
})
passport passport-jwt獲取token
// 在app.js里面引入
const passport = require("passport")
// passport 初始化
app.use(passport.initialize());
require("./config/passport")(passport)
在這里引入的文件里面 記住這里的內(nèi)容在引入的js里面
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
// 引入模型
const model = require('../model/model')
// 獲取模型
const User = model.getModle('user')
const keys = require("../config/keys");
const _filter = {pwd: 0, __v: 0}
const opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;
module.exports = (passport) => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.findById(jwt_payload.id, _filter)
.then(userData => {
if (userData) {
return done(null, userData)
}
return done(null, false)
})
.catch(err => console.log(err))
}))
}
// 然后接口調(diào)用的時(shí)候 //先當(dāng)當(dāng)前文件引入
const passport = require("passport")
// 這里的req.user就是默認(rèn)返回的值
Router.get('/info', passport.authenticate("jwt", {session: false}), function (req, res) {
// 首先拿到cookie校驗(yàn)
if (!req.user) {
return res.json({code: 1, msg: '驗(yàn)證token或者沒登錄信息'})
}
return res.json({code: 0, data: req.user})
})