Nest.js 在护照本地策略中获取请求 header

Nest.js get request header in passport local strategy

如何在护照本地策略中获取请求 headers? 我需要为每个实体使用一个单独的数据库,使用 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
        }
    }

您需要将 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
  }
}