![](/img/trans.png)
[英]Openiddict returning 404 instead of 401 for unauthorized web api calls (core 2.0)
[英].NET Core 3 (preview) Web API return UnAuthorized (401) instead of NotFound (404)
閱讀了許多帖子,博客和此SO線程后 ,此代碼無法完成我期望的操作:
services.AddAuthentication().AddCookie(options =>
{
options.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
context.Response.Clear();
context.Response.StatusCode = 401;
return Task.CompletedTask;
}
};
});
services.ConfigureApplicationCookie(options =>
{
options.Events.OnRedirectToLogin = context =>
{
context.Response.Clear();
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
};
});
API控制器的摘錄(使用authorize屬性):
[ApiController]
[Route("api/[controller]")]
[Authorize(Roles = "User")]
public class TravelPlanController : BaseController{
...
}
這是.NET Core 3.x(預覽)中Web API的啟動配置的一部分,應返回401未經授權 (本質上應為未經認證),但返回404 NotFound 。
404是由於以下事實導致的:默認的.NET Core身份驗證中間件重定向到/ auth / login之類的路由,並且該路由不可用(根據設計;這是API而不是MVC網站)。 因此,該請求是未經授權的,默認情況下會被重定向,並導致404:s
OnRedirectToLogin
處理程序的兩個方法都應攔截此默認行為(對於RESTfull API而言這是奇怪的),並返回簡單的401 UnAuthorized 。 但是他們沒有,在調試模式下不會遇到斷點,Postman和Chrome中的Angular應用都報告404 。
自.NET Core 3.x以來,有什么變化嗎? 還是其他人的解決方案從未真正起作用。
嘗試像對OnRedirectToLogin一樣在事件上定義OnRedirectToAccessDenied 。
這達到了目的:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<IdentityContext>()
.AddDefaultTokenProviders()
.AddRoles<IdentityRole>();
services.ConfigureApplicationCookie(options =>
{
options.Events.OnRedirectToLogin = context =>
{
context.Response.Headers["Location"] = context.RedirectUri;
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
});
使用ASP.NET Core 3.x (預覽版)和默認的Identity提供程序,可以使用上述聲明的指定順序來觸發OnRedirectToLogin
事件。
我也在這個SO線程中對此進行了闡述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.