I have a scenario where an app needs to authenticate a user by calling an API and sending a user token to verify user identity. I started working on a custom authentication handler based on the following tutorials:
I have a very basic example which right now simply fails the authentication just to make sure it works:
public class SoleAuthenticationHandler : AuthenticationHandler<SoleAuthenticationOptions>
{
private readonly ISoleApiService _soleApiService;
public SoleAuthenticationHandler(
IOptionsMonitor<SoleAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock, ISoleApiService soleApiService)
: base(options, logger, encoder, clock)
{
_soleApiService = soleApiService;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
return Task.FromResult(AuthenticateResult.Fail("You are not authorized to access this resource."));
}
}
This works as intended, controller actions decorated with [Authorize] attribute are intercepted and 401 is thrown. My questions are the following:
- How am I supposed to handle the 401 once it happens? For example let's say I want to redirect a user to a friendly page that says "you're not authorized please login". Is that something done in the handler or elsewhere? What is the proper process here? Looking at Microsoft docs for the AuthenticationHandler there is a method called BuildRedirectUri but providing that method with a uri does not really change anything - the page still returns a 401.
- As it stands now in order for this to work I need to decorate controllers/actions with [Authorize] attribute. Is there a way to do this globally so that I don't have to specifically authorize each controller and/or action?