Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select AuthGuard type on the fly

My app will use two different auth strategies - one for users using a browser and another for the public API. I'll set a header for those using a browser, and then my app will set the auth strategy based on the value of that header.

I have set up the two auth strategies, and given them names. I can now do this in my controller methods:

@Get()
@UseGuards(AuthGuard('strategy_name'))
async find() { }

What I would like to do, is NOT have to specify the auth guard type next to every controller method, nor the logic for determining which type to use. Instead, I'd like to put this logic in one place, which will be read by ALL calls to AuthGuard().

What's the best way to do this? Is there some kind of filter/hook/interceptor for AuthGuard?

like image 291
Dan. Avatar asked Sep 08 '25 03:09

Dan.


1 Answers

You can create a new Guard that acts as a delegate and chooses the proper AuthGuard (and therewith AuthStrategy) based on your condition.

@Injectable()
export class MyAuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const guard = this.getAuthGuard(context);
    return guard.canActivate(context);
  }

  private getAuthGuard(context: ExecutionContext): IAuthGuard {
    const request = context.switchToHttp().getRequest();

    // Here should be your logic to determine the proper strategy.
    if (request.header('myCondition')) {
      return new (AuthGuard('jwt'))();
    } else {
      return new (AuthGuard('other-strategy'))();
    }
  }

Then use it instead of the standard AuthGuard in your controller:

@UseGuards(MyAuthGuard)
@Get('user')
getUser(@User() user) {
  return {user};
}
like image 62
Kim Kern Avatar answered Sep 10 '25 13:09

Kim Kern