Custom Authorization Filter in .NET Core API

Shreyas Pednekar picture Shreyas Pednekar · Mar 11, 2019 · Viewed 9.7k times · Source

I want to authorize users before accessing any data using my core api, so I tried is using JWT authentication. I have successfully generated token while signing in user using api and saved that token on client side in session, now whenever user wants to access any data using api, I'll send that token in header to api and I want to validate that JWT token using custom authorization filter. I have created custom authorization filter and applied it on my GetMenu api and I'm able to validate that token successfully but after token validation in authorization filter it is not hitting it on my GetMenu api.

Here is my AccountController code:

[Filters.Authorization]
[AllowAnonymous]
[HttpPost]
[Route("GetMenu")]
public IActionResult GetMenu(string clientid, int rolecode, string repcode)
{
    //further process
}

Here is my Filters.Authorization code:

public class Authorization: AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext filterContext)
    {
        if (!ValidateToken(filterContext.HttpContext.Request.Headers["token"]))
        {
            filterContext.Result = new UnauthorizedResult();
        }
    }
}

I have breakpoints on OnAuthorization method and on GetMenu api. I'm calling my GetMenu api through postman to test, it is successfully hitting it on OnAuthorization method in Filters.Authorization and validating my JWT Token and displays Status Code: 200 in postman but after successful token validation it should hit on GetMenu api for further data processing but it is not hitting. What can be the issue? what am i missing? please help.

Answer

Edward picture Edward · Mar 12, 2019

You should not set the filterContext.Result if the request is successfully authorize.

//
// Summary:
//     A context for authorization filters i.e. Microsoft.AspNetCore.Mvc.Filters.IAuthorizationFilter
//     and Microsoft.AspNetCore.Mvc.Filters.IAsyncAuthorizationFilter implementations.
public class AuthorizationFilterContext : FilterContext
{
    //
    // Summary:
    //     Gets or sets the result of the request. Setting Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext.Result
    //     to a non-null value inside an authorization filter will short-circuit the remainder
    //     of the filter pipeline.
    public virtual IActionResult Result { get; set; }
}

You only need to set Result when it's failed.

public class Authorization: AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext filterContext)
    {
        if (!ValidateToken(filterContext.HttpContext.Request.Headers["token"]))
        {
            filterContext.Result = new UnauthorizedResult();
        }
    }
}