我有一个 ASP.NET Core (.NET 6) API 控制器,它确保只有经过身份验证的用户才能使用以下Authorize
属性访问其端点:
[ApiController]
[Authorize]
[Route("api/borrower")]
public class BorrowerController : ControllerBase
{
...
}
由于它提供 REST API,而不是返回 302 重定向响应,我更喜欢 401 未经身份验证的响应,因此我在以下位置配置了我的 cookie 身份验证Startup
:
services.AddScoped<CookieAuthenticationEventsHandler>();
services.ConfigureApplicationCookie(o =>
{
...
o.EventsType = typeof(CookieAuthenticationEventsHandler);
})
和:
public class CookieAuthenticationEventsHandler : CookieAuthenticationEvents
{
public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.FromResult(0);
}
}
按预期工作。我在未经身份验证的请求上得到 401 而不是 302。
当我引入基于角色的访问控制并将上面的内容更改为例如时,不起作用的是。[Authorize]
[Authorize(Roles = "Borrower")]
向具有经过身份验证但不再假定该角色的主体的控制器的请求导致 302 而不是 401。在RedirectToLogin
方法中设置断点表明在这种情况下没有调用该方法(即没有引发事件)。
此外,我没有看到任何其他适合这种情况的事件。
这是设计使然还是错误?我在这里错过了什么吗?我怎么还能把那个 302 变成 401。