繁体   English   中英

Cookie 身份验证问题 ASP.NET CORE 2.1。 AWS 负载均衡

[英]Cookie authentication issue ASP.NET CORE 2.1. AWS load balancing

更新:看起来下面的代码失败了:

services.AddDataProtection()
            .SetApplicationName(appname)
            .PersistKeysToRedis(redis, "DataProtectionKeys")
            .ProtectKeysWithCertificate(LoadCert(Configuration));

无法从 pfx 文件读取证书。

UPDATE2:哦,天哪! 证书文件已被 .gitignore 排除!:)) Live&Learn。 至少我们还活着,对吧!?;))


最初的问题:我在 Docker 容器中的 AWS 负载均衡器后面部署了 ASP.NET Core 2.1 应用程序。 当我尝试从登录页面登录应用程序时。 我收到 InvalidOperationException 的理由是:

未指定 authenticationScheme,也未找到 DefaultChallengeScheme。

但是当我再次点击相同的 URL 时,它实际上移动到了正确的页面并工作了一段时间,然后再次抛出相同的异常,HTTP 状态为 500,第二次尝试打开相同的页面后它成功了。 有趣的是,Chrome 不如 IE 健壮:如果 IE 在异常后无法恢复,Chrome 在后续提交页面时总是返回 404,从而产生上述异常。

因此,如果有人能够为我提供如何补救这种情况的想法,我将不胜感激 显然问题与身份验证有关,但我无法弄清楚应该做什么。

以下是 Startup.cs 中 ConfigureServices() 的相关应用:

        string appname = "MyApp";
        var redis = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("RedisConnection"));
        services.AddDataProtection()
            .SetApplicationName(appname)
            .PersistKeysToRedis(redis, "DataProtectionKeys")
            .ProtectKeysWithCertificate(LoadCert(Configuration));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddAuthentication( CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                    options =>
                    { 
                        options.LoginPath = new PathString("/Area/Ctrl/Login");
                        options.LogoutPath = new PathString("/Area/Ctrl/Logout");
                        options.Cookie.IsEssential = true;
                    });

        services.AddDistributedRedisCache(o =>
        {
            o.Configuration = Configuration.GetConnectionString("RedisConnection");
        });
        services.AddSession(options =>
        {
            options.Cookie.Name = appname;
            options.IdleTimeout = TimeSpan.FromSeconds(600);
        });

以下是 Startup.cs 中 Configure() 的相关代码:

        app.UseForwardedHeaders();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
             name: "areas",
             template: "{area:exists}/{controller=Ctrl}/{action=Login}/{id?}"
           );
        }); 

这是我在处理登录的控制器中设置主体的方式:

            ClaimsIdentity identity = new ClaimsIdentity(GetUserRoleClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            if (principal == null)
                throw new ApplicationException($"Could not create principal for {user?.UserName} user.");

            await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
            if (httpContext.User == null)
            {
                httpContext.User = principal;
            }

好的,现在一切正常。:) 这就是不同之处:

  1. 如果应用程序处于负载平衡状态,则所有实例都必须共享数据保护加密密钥(例如使用相同的密钥环)。 因此出现了 Redis 和证书。 会话也应该共享。 因此,Redis 再次出现。

  2. ProtectKeysWithCertificate()调用的证书应正确加载。 如果它无法加载,根本不要打电话,但这真的是个坏主意。 只要弄清楚为什么它没有加载。

  3. 避免在自定义身份验证 HttpContext 中抛出 InvalidOperationException。 应在登录操作中手动分配用户。

关于证书的一件重要事情:数据保护模块仅支持带有 CAPI 私钥的证书。 CNG 被留下了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM