asp.net-coreonactionexecuting

How to override "OnActionExecuting" defined in the Startup class inside a controller?


This code run for every incoming request to check whether it contains a valid JWT token.

services.AddMvc(options => 
       options.Filters.Add(typeof(JwtAttribute)));

That's what I want in most case, except for the first time (when the user is attempting to log in). Because it's running at every request, user can't log in.

I've tried to add an attribute on top of the login action, but it's still not working.

[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> Login([FromBody]Credentials formData)
{

}

What should I do to override the OnActionExecuting in the startup class just in this one case, so that user can log in.

Thanks for helping


Solution

  • By using a custom filter, instead of the built-in authentication and authorization system, you will not be able to use [AllowAnonymous] here since that is directly linked to the auth framework.

    What you can do is add additional metadata which you then check as part of your JwtAttribute filter. For example, create another attribute like so:

    public class DisableJwtAttribute : Attribute, IFilterMetadata
    { }
    

    You can now add this attribute to your controller action with [DisableJwt].

    And inside of your JwtAttribute filter, you can now check for that filter’s existence to stop processing the request. E.g. if your filter is an authorization filter, that would look like this:

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        if (context.Filters.Any(item => item is DisableJwtAttribute))
            return;
    
        // filter is active
    }
    

    That being said, the better solution would be to embrace the authentication system and have your JWT validation be part of the normal authentication process. That way, you could actually benefit from all the authentication and authorization things within ASP.NET Core.