Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the request url in the validate method of the http strategy?

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;
}
like image 321
RezaT1994 Avatar asked Mar 27 '19 11:03

RezaT1994


1 Answers

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

Edit Nest HTTP Auth

like image 170
Kim Kern Avatar answered Sep 30 '22 04:09

Kim Kern