繁体   English   中英

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

[英].NET Core cookie authentication with AWS Lambda not persisting

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

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

我已将 API 网关配置为使用 Visual Studio 的 AWS 扩展进行部署时设置的默认值。

我当前的 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);

@Alex Nazarevych 的回答是正确的,因为您需要设置数据保护存储。 但是, 链接的文章描述了如何将数据保护密钥存储在 AWS Systems Manager Parameter Store 中,而不是文件系统中。 这是有道理的,因为 Lambda 函数将不断退出并丢失其文件存储。

我在自己的网站上使用 AWS Parameter store,效果非常好。 这是您需要做的:

  1. Amazon.AspNetCore.DataProtection.SSM的 NuGet 包引用添加到您的项目。
  2. 在您的Startup.ConfigureServices方法中,添加以下代码。 您可以将"/DataProtection"更改为您喜欢的任何内容; 这只是定义了您的键名在 Parameter Store 中的开头:
services.AddDataProtection()
   .PersistKeysToAWSSystemsManager("/DataProtection");
  1. 确保您的 Lambda 函数对 AWS Parameter Store 具有AddTagsToResourcePutParameterGetParametersByPath权限。 作为 IAM 策略,它看起来如下所示。 请注意,如果您在上面的代码中使用了"/DataProtection"以外的内容,那么您需要更改下面策略中的资源以匹配。 (不要忘记末尾的星号。)
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "ssm:AddTagsToResource",
                "ssm:GetParametersByPath",
                "ssm:PutParameter"
            ],
            "Resource": "arn:aws:ssm:*:*:parameter/DataProtection*",
            "Effect": "Allow"
        }
    ]
}

代码运行一次后,您可以使用 AWS 控制台自行查看密钥。 只需登录 AWS 控制台并导航至Systems Manager Parameter Store

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

要解决您需要设置数据保护存储的问题,例如(请参阅有关 ms docs的文章):

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

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

[警告] Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository:使用内存存储库。 密钥不会持久存储。

[警告] Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager:用户配置文件和 HKLM 注册表均不可用。 使用临时密钥存储库。 当应用程序退出时,受保护的数据将不可用。

请参阅本文了解如何在 AWS Lambda 中为 asp.net core 配置 DataProtection

暂无
暂无

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

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