I want to access the context object that exists in guards, inside my bearer strategy validate method. Can I pass it as an argument alongside with the token?
bearer-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;
}
}
I want something like this:
async validate(token: string, context) { // <-- context object as argument
const customer = await this.globalService.validateCustomer(token);
if (!customer) {
throw new UnauthorizedException();
}
return customer;
}
You can access the request
object by passing the option passReqToCallback: true
to passport-http-bearer
. Then the first parameter in your validate callback will be the 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;
}
}
See a running demo here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With