我有一个 SPA,我希望升级到 .NET Core 2.0 Web API
开箱即用的 .NET Core 对 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()
按照建议in the official docs ,但这些设置只是被忽略了。 services.Configure<CookieAuthenticationOptions>
行为方式相同。
如何设置 .NET Core 2.0 Web API,以便在请求没有有效的身份验证 cookie 时返回 HTTP 401 状态?
最佳答案
在 Authentication 2.0 堆栈中,应用程序 cookie 的配置不再是 identityOptions 的一部分。请看Auth 2.0 Changes
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;
}
};
});
关于.net - 将 SPA 中的 cookie 身份验证升级到 .NET Core 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45729477/