gpt4 book ai didi

api - .net core - 如何在 AuthorizationHandler 上返回 403?

转载 作者:行者123 更新时间:2023-12-03 19:46:49 24 4
gpt4 key购买 nike

我实现了我的自定义 AuthorizationHandler。
对此,我检查用户可以解决并处于事件状态。

如果用户不活跃,那么我想返回 403 状态。

protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidUserRequirement requirement)
{
var userId = context.User.FindFirstValue( ClaimTypes.NameIdentifier );

if (userId != null)
{
var user = await _userManager.GetUserAsync(userId);

if (user != null)
{
_httpContextAccessor.HttpContext.AddCurrentUser(user);

if (user.Active)
{
context.Succeed(requirement);
return;
}
else
{
_log.LogWarning(string.Format("User ´{1}´ with id: ´{0} isn't active", userId, user.UserName), null);
}
}
else
{
_log.LogWarning(string.Format("Can't find user with id: ´{0}´", userId), null);
}
} else
{
_log.LogWarning(string.Format("Can't get user id from token"), null);
}

context.Fail();

var response = _httpContextAccessor.HttpContext.Response;
response.StatusCode = 403;

}

但是我收到了 401。你能帮帮我吗?

最佳答案

你能在你的函数结束时检查一下吗?我在我的自定义中间件中使用它在某些情况下将状态代码重写为 401,但在您的场景中也应该有效

var filterContext = context.Resource as AuthorizationFilterContext;
var response = filterContext?.HttpContext.Response;
response?.OnStarting(async () =>
{
filterContext.HttpContext.Response.StatusCode = 403;
//await response.Body.WriteAsync(message, 0, message.Length); only when you want to pass a message
});

关于api - .net core - 如何在 AuthorizationHandler 上返回 403?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51668710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com