[英]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.