【发布时间】:2017-09-25 12:22:43
【问题描述】:
我有一个使用 cookie 身份验证的 .NET 核心 API。它由具有自己的登录路径的 PWA/SPA 访问。
在Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddIdentity<MyUser, MyRole>(options =>
{
...
// Use cookie authentication
var expiresIn = new TimeSpan(1, 0, 0); // 1 hour timeout
var c = options.Cookies.ApplicationCookie;
c.AuthenticationScheme = "appSchemeName";
c.CookieName = "appCookieName";
c.AutomaticAuthenticate = true;
// If this is true auth failures become redirects
c.AutomaticChallenge = false;
c.SlidingExpiration = true;
c.ExpireTimeSpan = expiresIn;
// Store sessions in the cache with the same TTL as the cookie
c.SessionStore = new MyRedisSessionStore(expiresIn);
});
...
}
public void Configure(...)
{
...
app.UseIdentity();
...
app.UseMvc();
}
在我的客户端 JS 中,当身份验证 cookie 无效或丢失时,我希望出现 401,并在这种情况下显示登录表单。
但是,当没有有效 cookie 的用户访问标有 [Authorize] 的控制器时,他们会收到 500 状态错误:
InvalidOperationException:没有配置身份验证处理程序来处理方案:自动
如果我更改 c.AutomaticChallenge = true;,那么我会收到一个 302 重定向到 {site}/Account/Login?ReturnUrl={api resource it was trying to load}。这很奇怪,因为那不是有效的路线,而且我没有设置它。
如何解决此问题,以便未经身份验证的用户在服务器上获得 401 而不是 500 异常。
我意识到我可以覆盖它并使用自定义响应编写自己的身份验证,但必须有办法让内置的 [Authorize] 返回正确的 HTTP 状态代码。
【问题讨论】:
-
您是否尝试过在运行时一次单步执行代码以查看它在哪一行中断?
-
@sam 微软的中间件在它到达我的代码之前就抛出了错误。
标签: .net authentication asp.net-web-api asp.net-core http-status-code-401