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
?
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};
}
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