http策略的validate方法中如何访问请求url?

Rez*_*994 6 javascript node.js typescript passport.js nestjs

我想访问存在于守卫中的上下文对象,在我的承载策略验证方法中。我可以将它作为参数与令牌一起传递吗?

Bearer-auth.guard.ts:

@Injectable()
export class BearerAuthGuard extends AuthGuard('bearer') {
    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
        return super.canActivate(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

http.strategy.ts:

@Injectable()
export class HttpStrategy extends PassportStrategy(Strategy) {
    constructor(private globalService: GlobalService) {
        super();
    }

    async validate(token: string) {
        const customer = await this.globalService.validateCustomer(token);
        if (!customer) {
            throw new UnauthorizedException();
        }
        return customer;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西:

async validate(token: string, context) { // <-- context object as argument
    const customer = await this.globalService.validateCustomer(token);
    if (!customer) {
        throw new UnauthorizedException();
    }
    return customer;
}
Run Code Online (Sandbox Code Playgroud)

Kim*_*ern 9

您可以访问request通过将选择对象passReqToCallback: truepassport-http-bearer。然后验证回调中的第一个参数将是request

@Injectable()
export class HttpStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    // Add the option here
    super({ passReqToCallback: true });
  }

  async validate(request: Request, token: string) {
    // Now you have access to the request url
    console.log(request.url);
    const user = await this.authService.validateUser(token);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
Run Code Online (Sandbox Code Playgroud)

在此处查看正在运行的演示

编辑 Nest HTTP 身份验证