更新:以下代码似乎失败了:
services.AddDataProtection()
.SetApplicationName(appname)
.PersistKeysToRedis(redis, "DataProtectionKeys")
.ProtectKeysWithCertificate(LoadCert(Configuration));
无法从 pfx 文件读取证书。
更新2: 天啊!证书文件已被 .gitignore 排除!:)) Live&Learn。至少我们还活着,对吧!?;))
初始问题: 我在 Docker 容器中的 AWS 负载均衡器后面部署了 ASP.NET Core 2.1 应用程序。 当我尝试从登录页面登录应用程序时。我收到 InvalidOperationException 的理由是:
No authenticationScheme was specified, and there was no DefaultChallengeScheme found.
但是当我再次点击相同的 URL 时,它实际上会移动到正确的页面并工作一段时间,然后再次抛出相同的异常,HTTP 状态为 500 在第二次尝试打开同一页面后,它成功了。有趣的是,Chrome 并不像 IE 那样健壮:如果 IE 在异常后无法恢复,Chrome 在后续提交页面时总是返回 404,从而产生了上述异常。
So I would appreciate, if somebody would be able to provide me with ideas how to remedy the situation Obviously issue is related to the authentication, but I could not figure out exactly what should be done.
以下是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?}"
);
});
以下是我在 Controller 中设置主体的方式,该 Controller 处理登录:
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;
}
最佳答案
好的,现在一切正常。:) 这就是造成差异的原因:
如果应用程序处于负载平衡状态,所有实例都必须共享数据保护加密 key (例如使用相同的 key 环)。因此出现了 Redis 和证书。 session 也应该共享。于是Redis又来了。
ProtectKeysWithCertificate()
调用的证书应正确加载。如果无法加载,则根本不要进行该调用,但这将是一个非常糟糕的主意。只要弄清楚为什么它没有加载即可。为了避免在自定义身份验证 HttpContext 中引发 InvalidOperationException。应在登录操作中手动分配用户。
关于证书的一个重要事项:数据保护模块仅支持具有 CAPI 私钥的证书。 CNG 被抛在后面。
关于c# - ASP.NET CORE 2.1 的 Cookie 身份验证问题。 AWS负载均衡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54465832/