Reputation: 784
I'm using a custom AuthenticationHandler
and only some of my controller methods have the [Authorize]
attribute. I log on Info level and it creates a log entry for any method call. Now I can't tell apart if somebody actually tried accessing a method that requires authorization and failed or if it's a call to a method that doesn't even need authorization and it fails because it's supposed to.
Is there a way to tell them apart or preferably to keep MVC from calling HandleAuthenticateAsync
when it's not needed?
Upvotes: 5
Views: 3891
Reputation: 1
I added this in the beginning my Handler;
// skip authentication if endpoint has [AllowAnonymous] attribute
var endpoint = Context.GetEndpoint();
if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
return AuthenticateResult.NoResult();
and of course added [AllowAnonymous] to the controller
Upvotes: 0
Reputation: 1662
It sounds like you might be misusing the AuthenticationHandler
. You are not supposed to immediately reject access if the user fails to authenticate. If you do so, it doesn't even reach the MVC context in the pipeline.
Unless you intentionally want to reject any access to unauthenticated users, you should only either authenticate or pass it through as anonymous user. After that at some point AuthorizeAttribute
will kick in and check whether user has access to the requested resource or not. If he is not authenticated, the authorization will reject the request.
Upvotes: 5