我想在我的承载策略验证方法中访问保护中存在的上下文对象。我可以将它作为参数与令牌一起传递吗?
承载-auth.guard.ts:
@Injectable()
export class BearerAuthGuard extends AuthGuard('bearer') {
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
return super.canActivate(context);
}
}
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;
}
}
我想要这样的东西:
async validate(token: string, context) { // <-- context object as argument
const customer = await this.globalService.validateCustomer(token);
if (!customer) {
throw new UnauthorizedException();
}
return customer;
}
您可以通过将选项request
传递给passReqToCallback: true
来访问passport-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;
}
}
在这里查看正在运行的演示