【发布时间】:2017-08-17 07:53:39
【问题描述】:
我有一个想要升级到 .NET Core 2.0 Web API 的 SPA
开箱即用的 .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 将被忽略。
我已尝试按照建议的in the official docs 将其移至services.AddAuthentication(...).AddCookie(),但这些设置被忽略了。 services.Configure<CookieAuthenticationOptions> 的行为方式相同。
如何设置 .NET Core 2.0 Web API,以便在请求没有有效的身份验证 cookie 时返回 HTTP 401 状态?
【问题讨论】:
-
SPA 总是有问题的工作表单/cookies 身份验证,反之亦然。如果你做 SPA,那么做 JSON Web Tokens Authentication 并将所有后端服务作为 Web API 运行。
-
@Jeyara 你说得好像这是 SPA 的一个基本问题。它不是。 Cookies != 表单,服务是否返回不记名令牌或 cookie 应该是一个实现细节,而不是锁定用户名/密码请求是表单还是 JSON 帖子。这甚至不是这里的问题:我有一个 SPA 可以与其中任何一个一起使用(两者都受支持,因此一些密码管理器可以工作)并且成功地从 1.1 设置了 cookie,但是在 2 中失败了,因为它假设我总是想要一个表单重定向。
标签: .net authentication .net-core .net-core-2.0