Passport.js认证异常:请求全拒或无差别通过问题排查
Passport.js JWT身份验证异常排查求助
问题现象
- 当
auth方法采用如下写法时,所有请求均返回"unauthorized"(未授权):
import passport from 'passport' import passportJWT from 'passport-jwt' import userModel from '../user/user.model' import {Request, Response, NextFunction} from 'express' export default class PassportController{ static async setup(app: express.Application){ const JWTStrategy = passportJWT.Strategy const ExtractJwt = passportJWT.ExtractJwt const config = { jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: process.env.JWT_SECRET, issuer: 'DepoApp', } passport.use(userModel.createStrategy()) passport.use(new JWTStrategy( config, (payload, done) => { userModel.findOne({_id: payload.id}, (err:any, user:any) => { if(err) { return done(err, false) } else if(user){ return done(null, user) } else{ return done(null, false) } }) } )) } static async auth(req: Request, res: Response, next: NextFunction){ await passport.authenticate('jwt', {session: false})(req, res, next) } }
- 将
auth方法修改为如下形式后,无论token是否有效,所有请求均被授权:
static async auth(req: Request, res: Response, next: NextFunction){ await passport.authenticate('jwt', {session: false}) next() }
推测问题源于auth中间件配置不当,请求协助排查。
相关配置信息
- 未使用会话(session)
- 用户模型使用
_id作为标识,无username字段,模型代码如下:
import mongoose from 'mongoose' import { Schema } from 'mongoose' import Permits from './permits.enum' import passportLocalMongoose from 'passport-local-mongoose' const userSchema = new Schema({ _id: {type: String}, //album number (Organisation specific ID) first_name: {type: String, required: true}, last_name: {type: String, required: true}, phone: {type: String, required: true}, mail: {type: String, required: true, lowercase: true, trim: true, unique: true}, permits: [{type: String, enum: Permits, default: []}], }, { collection: 'users', timestamps: true, }) userSchema.plugin(passportLocalMongoose, {usernameField: '_id'}) const userModel = mongoose.model('User', userSchema) export default userModel
- 路由配置如下:
this.app.route('/api/depo') .get(PassportController.auth, DepoController.getAll) .post(PassportController.auth, DepoController.post) this.app.route('/api/depo/:id') .get(PassportController.auth, DepoController.getById) .patch(PassportController.auth, DepoController.patchById) .delete(PassportController.auth, DepoController.deleteById) this.app.route('/api/no-gdpr/depo/') .get(DepoController.getAllNoGDPR) this.app.route('/api/no-gdpr/depo/:id') .get(DepoController.getOneNoGDPR)
已尝试操作
修改auth方法及JWTStrategy内容,但JWTStrategy中的payload无输出,仿佛未被调用。
内容的提问来源于stack exchange,提问作者Tomasz Topoła
相关产品推荐
相关产品推荐

