Nest.js在passport本地策略中获取请求头

Dan*_*evy 4 mongodb node.js jwt passport.js nestjs

如何获取护照本地策略中的请求标头?我需要使用 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
        }
    }

Run Code Online (Sandbox Code Playgroud)

Jay*_*iel 19

您需要添加passReqToCallback: truesuper构造函数中的调用。这将使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
  }
}
Run Code Online (Sandbox Code Playgroud)