You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Passport.js认证异常:请求全拒或无差别通过问题排查

Passport.js JWT身份验证异常排查求助

问题现象

  1. 当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)
    }
}
  1. 将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:57:54