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

时间:2017-08-17 07:53:40

标签: .net authentication .net-core .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将被忽略。

我已按照建议in the official docs尝试将其移至services.AddAuthentication(...).AddCookie(),但这些设置只是被忽略了。 services.Configure<CookieAuthenticationOptions>的行为方式相同。

如何设置.NET Core 2.0 Web API,以便在请求没有有效的身份验证cookie时返回HTTP 401状态?

1 个答案:

答案 0 :(得分:0)

在Authentication 2.0堆栈中,应用程序cookie的配置不再是identityOptions的一部分。请参阅Auth 2.0 Changes

sudo yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-xxx-xxxx.noarch.rpm