在koa项目中安装koa-passport
yarn add koa-passport -D
在app.js入口文件引入和使用
// token验证
const passport = require('koa-passport');
// token验证
app.use(passport.initialize());
app.use(passport.session());
// 回调到指定config文件 passport.js中
require('./config/passport')(passport);
在 config\passport.js 文件中进行token验证逻辑处理
const JwtStrategy = require('passport-jwt').Strategy;
const JwtExtractJwt = require('passport-jwt').ExtractJwt;
const keys = require('./keys');
const options = {};
options.jwtFromRequest = JwtExtractJwt.fromAuthHeaderAsBearerToken();
options.secretOrKey = keys.secretOrKey;
const mongoose = require('mongoose');
const User = mongoose.model('users');
module.exports = (passport) => {
passport.use(
new JwtStrategy(options, async (jwt_payload, done) => {
const user = await User.findById(jwt_payload.id);
//查询当前用户是否有权限
if (user) {
return done(null, user);
} else {
return done(null, false);
}
})
);
};
在文件routes\login.js中写一个私有接口 进行测试
// token验证
router.get(
'/currentToken',
passport.authenticate('jwt', { session: false }),
async (ctx) => {
const { id, username, avatar, email } = ctx.state.user;
ctx.body = {
id,
username,
avatar,
email,
};
}
);
在postman上调用试一下 (本地服务器,自己替换成自己的服务器即可)
http://localhost:5000/users/currentToken
header设置一下 Authorization:
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYxODVmZmQ1ODM5YmIzYjQ0ODhhMDQyMiIsIm5hbWUiOiI2NDlmMzE4OGRkYzc5NmVmNDA3OTA2MDFhNjA0YWFlMCIsImF2YXRhciI6IjI1ZDU1YWQyODNhYTQwMGFmNDY0Yzc2ZDcxM2MwN2FkIiwiaWF0IjoxNjM2MTgxMzc3LCJleHAiOjE2MzYxODQ5Nzd9.cikFwOBNWQQ_cID70RqSngDLTbwZoHQqHcjyar6cFQE
测试接口返回 Unauthorized 代表当前的用户没有权限或者token不对
反之,返回用户基本信息如下,代表token验证通过
{
"id": "6185ffd5839bb3b4488a0422",
"username": "649f3188ddc796ef40790601a604aae0",
“avatar”:"",
"email":"123232@aliyun.com"
}