我想检查访问令牌是否在黑名单中,然后返回Unauthorized。
public class CheckBannedTokenAttribute : Attribute, IAsyncAuthorizationFilter
{
public Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (TokenInBlackList("232322323"))
{
//context.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
}
}
}
答案 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();
}
}