Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return status code with an authorization filter

I want to check if the access token is in the blacklist, and then return Unauthorized.

public class CheckBannedTokenAttribute : Attribute, IAsyncAuthorizationFilter
{
    public Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        if (TokenInBlackList("232322323"))
        {
            //context.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
        }
    }
}
like image 523
Jhon Duck Avatar asked Oct 20 '25 09:10

Jhon Duck


2 Answers

You are right that you need to fill context.Result. Cause you want to return 401 Unauthorized as response, use built-in UnauthorizedResult class:

if (TokenInBlackList("232322323"))
{
   context.Result = new UnauthorizedResult();
   return Task.CompletedTask;
}

In general, this is the same as new StatusCodeResult(401)

like image 129
Set Avatar answered Oct 21 '25 23:10

Set


This will give you the classic "401 Unauthorized" that you expect.

async Task IAsyncAuthorizationFilter.OnAuthorizationAsync(AuthorizationFilterContext context)
{
    ClaimsPrincipal user = context.HttpContext.User;

    if (!user.Identity.IsAuthenticated)
    {
        context.Result = new ChallengeResult();
    }
}
like image 37
Zach J. Avatar answered Oct 22 '25 01:10

Zach J.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!