缺少Cookie时.NET Core返回500而不是401 [英] .NET core returning 500 instead of 401 when missing cookie

查看:226
本文介绍了缺少Cookie时.NET Core返回500而不是401的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Cookie身份验证的.NET核心API.具有自己的登录路线的PWA/SPA可以访问它.

I have a .NET core API that uses cookie authentication. It is accessed by a PWA/SPA that has its own login route.

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,并在这种情况下显示登录表单.

In my client side JS I expect a 401 when the authentication cookie is invalid or missing, and display a login form when this is the case.

但是,当没有有效cookie的用户访问标有[Authorize]的控制器时,他们将收到500状态错误:

However, when a user without a valid cookie visits a controller flagged with [Authorize] they get a 500 status error:

InvalidOperationException:未配置身份验证处理程序来处理方案:自动

InvalidOperationException: No authentication handler is configured to handle the scheme: Automatic

如果我更改c.AutomaticChallenge = true;,则将收到302重定向到{site}/Account/Login?ReturnUrl={api resource it was trying to load}.这很奇怪,因为这不是有效的路线,而且我没有设置它.

If I change c.AutomaticChallenge = true; then I get a 302 redirecting to {site}/Account/Login?ReturnUrl={api resource it was trying to load}. That's weird because that's not a valid route and I didn't set it.

如何解决此问题,以便未经身份验证的用户在服务器上收到401而不是500的异常.

How do I fix this so that unauthenticated users get a 401 instead of a 500 exception on the server.

我意识到我可以重写它并使用自定义响应编写我自己的身份验证,但是必须有一种方法使内置的[Authorize]返回正确的HTTP状态代码.

I realise that I can override this and write my own authentication with custom responses, but there must be a way to make the built-in [Authorize] return the correct HTTP status code.

推荐答案

当我使用Postman测试端点时遇到了这个确切的问题.

I ran into this exact issue when I was using Postman to test my endpoints.

如果您查看OnRedirectToLogin事件的nofollow noreferrer>源代码,您可以看到它正在检查该请求是否为AJAX请求.为了使IsAjaxRequest返回trueX-Requested-With标头必须具有XMLHttpRequest作为其值.

If you look at the source code for the OnRedirectToLogin event, you can see that it is checking if the request is an AJAX request. For IsAjaxRequest to return true, the X-Requested-With header needs to have XMLHttpRequest as it's value.

如果您恰好要用Postman进行测试,则必须手动将X-Requested-With和正确的值一起应用:

If you happen to be testing this out with Postman, you'll have to manually apply the X-Requested-With along with the correct value:

最后,如果没有其他需要设置的特殊配置,这就是CookieAuthenticationOptions的外观:

Finally, this is what your CookieAuthenticationOptions should look like if you have no other special configurations that need to be set:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
});

这篇关于缺少Cookie时.NET Core返回500而不是401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆