【问题标题】:Nest.js get request header in passport local strategyNest.js 在护照本地策略中获取请求标头
【发布时间】:2021-09-11 17:49:46
【问题描述】:

如何在护照本地策略中获取请求标头? 我需要为每个实体使用一个单独的数据库,使用 mongodb,所以我需要一种在身份验证之前获取子域的方法,以确定我应该连接到的数据库

    @Injectable()
    export class LocalStrategy extends PassportStrategy(Strategy) {
        constructor(private authService: AuthService) {
            super({ usernameField: 'email' })
        }
    
        async validate(email: string, password: string, headers:Headers): Promise<IUser> {
            //** this is what I want to have
            //** const subdomain = headers.host.split(".")[0]
            const user = await this.authService.validateUser({ email, password ,//** subdomain})
            if (!user) {
                throw new UnauthorizedException()
            }
            return user
        }
    }

【问题讨论】:

    标签: node.js mongodb jwt passport.js nestjs


    【解决方案1】:

    您需要将passReqToCallback: true 添加到构造函数中的super 调用中。这将使req 成为validate 的第一个参数,因此您可以执行类似的操作

    @Injectable()
    export class LocalStrategy extends PassportStrategy(Strategy) {
      constructor(private authService: AuthService) {
        super({ usernameField: 'email', passReqToCallback: true })
      }
    
      async validate(req: Request, email: string, password: string, headers:Headers): Promise<IUser> {
        const subdomain = req.headers.host.split(".")[0];
        const user = await this.authService.validateUser({ email, password ,//** subdomain})
        if (!user) {
          throw new UnauthorizedException()
        }
        return user
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-29
      • 2016-05-29
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      相关资源
      最近更新 更多