[英]Upgrading cookie authentication in a SPA to .NET Core 2.0
我有一個SPA我希望升級到.NET Core 2.0 Web API
開箱即用.NET對於SPA的cookie身份驗證非常糟糕,因為所有中間件都假定您要重定向到/Account/Login
。
在單頁面應用程序中,身份驗證重定向是無用的(沒有登錄頁面) - 而是我需要一個401響應,告訴客戶端JS要求用戶登錄。
要在.NET Core 1.1中解決此問題,我必須允許觸發AutomaticChallenge
然后覆蓋事件...
services.AddIdentity<AppUser, AppRole>(options =>
{
var c = options.Cookies.ApplicationCookie;
c.AuthenticationScheme = "MyScheme";
c.CookieName = "MyCookieName";
c.AutomaticAuthenticate = true;
// This is a total cludge: AutomaticChallenge causes something deep in .NET to auto respond with a 302 redirect to ~/account/login
c.AutomaticChallenge = true;
c.LoginPath = PathString.Empty; // LoginPath defaults to ~/account/login
c.Events = new CookieAuthenticationEvents
{
// Override the 302 redirection with the 401 we actually want
OnRedirectToLogin = context =>
{
context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
return Task.FromResult(0);
}
};
})
這是一個淤泥,但它起作用了。 在.NET Core 2.0中,它已被棄用。
我已嘗試將其移至services.ConfigureApplicationCookie
,但在配置cookie名稱和其他屬性時,將忽略CookieAuthenticationEvents.OnRedirectToLogin
。
我已經嘗試將其移動到services.AddAuthentication(...).AddCookie()
如官方文檔中所建議的那樣 ,但這些設置只是被忽略了。 services.Configure<CookieAuthenticationOptions>
行為方式相同。
如何設置.NET Core 2.0 Web API,以便在請求沒有有效的身份驗證cookie時返回HTTP 401狀態?
在Authentication 2.0堆棧中,應用程序cookie的配置不再是identityOptions的一部分。 請參閱Auth 2.0更改
services.ConfigureApplicationCookie(o =>
{
o.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = (ctx) =>
{
if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = 401;
}
return Task.CompletedTask;
},
OnRedirectToAccessDenied = (ctx) =>
{
if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = 403;
}
return Task.CompletedTask;
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.