使用授权过滤器返回状态代码

时间:2018-04-18 11:36:18

标签: c# asp.net-core

我想检查访问令牌是否在黑名单中,然后返回Unauthorized。

public class CheckBannedTokenAttribute : Attribute, IAsyncAuthorizationFilter
{
    public Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        if (TokenInBlackList("232322323"))
        {
            //context.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
        }
    }
}

3 个答案:

答案 0 :(得分:0)

您的代码似乎都很好,只需初始化Response并返回Task

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

答案 1 :(得分:0)

你是对的,你需要填写context.Result。因为您希望将401 Unauthorized作为回复返回,请使用内置的UnauthorizedResult类:

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

通常,这与new StatusCodeResult(401)

相同

答案 2 :(得分:0)

这将为您提供您期望的经典“401 Unauthorized”。

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

    if (!user.Identity.IsAuthenticated)
    {
        context.Result = new ChallengeResult();
    }
}