如何在http策略的validate方法中访问请求url?
How to access the request url in the validate method of the http strategy?
我想在我的承载策略验证方法中访问守卫中存在的上下文对象。我可以将它作为参数与令牌一起传递吗?
承载-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;
}
您可以通过将选项 passReqToCallback: true
传递给 passport-http-bearer
来访问 request
对象。那么验证回调中的第一个参数将是 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;
}
}
在此处查看 运行 演示
我想在我的承载策略验证方法中访问守卫中存在的上下文对象。我可以将它作为参数与令牌一起传递吗?
承载-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;
}
您可以通过将选项 passReqToCallback: true
传递给 passport-http-bearer
来访问 request
对象。那么验证回调中的第一个参数将是 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;
}
}
在此处查看 运行 演示