mongoose Passport.js对所有请求返回unauthorized,或者不管token是什么都授权

e5nszbig  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(103)

我的Passsport.js函数无法对用户进行身份验证。
在这种形式下,它为所有请求返回“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方法更改为下面的形式时,它会授权所有用户,而不管他们的令牌如何:

static async auth(req: Request, res: Response, next: NextFunction){
        await passport.authenticate('jwt', {session: false})
        next()
    }


我认为这是由于中间件auth的形式不正确造成的,所以请帮助我配置它。
index.ts中,我简单地调用PassportController.setup()
注意#1:我没有使用会话
注#2:我使用_id作为默认键,用户模型没有用户名字段,因为组织已经有了用户ID的数据库。用户型号:

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


我已经尝试过用各种方法更改auth方法,如上所述。我还尝试更改JWTStrategy()的内容,令人惊讶的是console.log(payload)不打印任何内容(它只是空的,好像函数从未被调用过)。
在类似的问题中,这里有一个路线问题,但在我的情况下,一切都是因为它应该是。
路线:

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)

czfnxgou

czfnxgou1#

我解决了!
有两个主要错误导致了这种情况。

  1. JWT令牌没有issuer属性,因此整个策略被跳过,因为passport.js已经拒绝了请求。这就是为什么我删除了发行者字段表单config
const config = {
     jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
     secretOrKey: process.env.JWT_SECRET,
}

字符串
然后另一个错误发生了-mongoose v。5.* 撤销了findOne()方法的回调。出于这个原因,我不得不稍微重构一下Strategy回调函数:

const JWTstrategy = new passportJWT.Strategy(
    config, 
    (payload, done) => {
        var user
        try{
            user = userModel.findOne({_id: payload.user._id})
        }catch(err){
            return done(err, false)
        }
        if(user){
            return done(null, user)
        }
        else{
            return done(null, false)
        }
    }
)


所以现在整个setup函数看起来像这样:

static async setup() {

      const ExtractJwt = passportJWT.ExtractJwt

      const config = {
        jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
        secretOrKey: process.env.JWT_SECRET,
      }

      const JWTstrategy = new passportJWT.Strategy(
        config,
        (payload, done) => {
          var user
          try {
            user = userModel.findOne({
              _id: payload.user._id
            })
          } catch (err) {
            return done(err, false)
          }
          if (user) {
            return done(null, user)
          } else {
            return done(null, false)
          }
        }
      )

      passport.use(userModel.createStrategy())
      passport.use('jwt', JWTstrategy)

      console.log('[PASSPORT]: setup finished.')
    }

相关问题