Jhon Duck
Jhon Duck

Reputation: 377

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);
        }
    }
}

Upvotes: 4

Views: 4493

Answers (3)

Zach J.
Zach J.

Reputation: 214

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();
    }
}

Upvotes: 1

Set
Set

Reputation: 49779

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)

Upvotes: 4

manish
manish

Reputation: 1458

your code seems all good, simply initialize the Response and return Task

if (TokenInBlackList("232322323")){
    context.Response = context.Request.CreateResponse(HttpStatusCode.Unauthorized);
    return Task.FromResult<object>(null);
}

Upvotes: -1

Related Questions