.net - 将 SPA 中的 cookie 身份验证升级到 .NET Core 2.0

标签 .net authentication .net-core .net-core-2.0

我有一个 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/

相关文章:

authentication - 如何从断开的网络生成 SSL 客户端证书?

c# - EF Core 和大流量导致达到最大池大小错误

c# - 将多个模型的一个实例映射到 EF Core 中的一个属性

c# - 以编程方式重新启动 IIS7 (C#)

c# - 为什么这个程序会挂起?

http - 是否有 "classic"cookie 身份验证的可行替代方案?

laravel:如何保持登录直到条件变为假?

.net - 存储过程的 MySQL .NET 连接器问题

c# - 如果我在 SqlConnection 的 using 语句中捕获异常,using 是否仍然处理关闭和处理我的连接?

c# - 如何在 oData .Net core 3.1 中启用 $levels