gpt4 book ai didi

c# - .NET Core cookie 身份验证与 AWS Lambda 不持久

转载 作者:行者123 更新时间:2023-12-04 12:40:49 25 4
gpt4 key购买 nike

我无法通过使用 .NET Core 2.1 MVC 的 AWS Lambda 函数进行 cookie 身份验证。

我尝试了很多 cookie 选项的变体。我能够登录并看到响应中创建的 asp cookie,但通常在我刷新或单击任何链接后返回到登录屏幕,例如对服务器的下一个请求。 *更新:似乎我现在处于一种状态,我现在只需要登录两次并且它保持登录状态。这也是使用 .net 2.1 的第二个 Lambda 函数,我注意到了这种行为。

我配置了使用 AWS 扩展部署 Visual Studio 时设置的默认值的 API 网关。

我当前的 startup.cs 代码,适用于本地主机:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
// Cookie settings
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.LoginPath = "/Login";
options.LogoutPath = "/Logout";
options.AccessDeniedPath = "/Login";
options.Cookie.Name = "myapp.auth";
options.Cookie.HttpOnly = true;
options.Cookie.Expiration = TimeSpan.FromDays(1);
});

services.ConfigureApplicationCookie(options =>
{
// Cookie settings, only this changes expiration
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromDays(1);
});
services.AddAntiforgery(options => { options.Cookie.Expiration = TimeSpan.Zero; });


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();

app.UseMvc();
}

我在登录时也尝试使用以下内容:
    await HttpContext.SignInAsync(principal, new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddHours(12),
IsPersistent = true
});

只需使用以下内容即可让我保持登录状态,但我必须在 cookie 保留之前登录两次(在单击任何内容并被重定向到再次登录后再次登录):
await HttpContext.SignInAsync(principal);

最佳答案

发生这种情况是因为 AWS Lambda 中托管的应用程序会定期退出,从而导致 DataProtection 服务忘记您的 cookie key 。因此,即使您的应用程序客户端确实发送了 cookie,服务器也会在重新启动后拒绝它,因为数据保护 key 已更改。

要解决该问题,您需要设置数据保护存储,例如作者(见文章 on ms docs):

services.AddDataProtection()
.PersistKeysToFileSystem("{PATH TO COMMON KEY RING FOLDER}")
.SetApplicationName("SharedCookieApp");

我在 AWS lambda 上运行 asp.net core 3.1 时遇到了类似的问题。当我检查日志时,有几个非常具有描述性的警告消息:

[Warning] Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository: Using an in-memory repository. Keys will not be persisted to storage.

[Warning] Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager: Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.



this article关于如何在 AWS Lambda 中为 asp.net core 配置数据保护

关于c# - .NET Core cookie 身份验证与 AWS Lambda 不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55886436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com