【问题标题】:IdentityServer4 (v3.1.x) Entity Framework - Session not persistentIdentityServer4 (v3.1.x) 实体框架 - 会话不持久
【发布时间】:2021-12-26 13:50:42
【问题描述】:

我将 IdentityServer4 (v3.1.x) 与 Entity Framework 包一起使用,以允许将配置和操作设置存储在数据库中。然而,我注意到,出于某种原因,用户登录 IS4 的持续时间由 IIS 应用程序池的“回收间隔”设置决定,我目前将其设置为 30 分钟。这与用户会话的预期行为不同,只要 access_token 持续时间 / refresh_token 持续时间允许。

当 IIS 应用程序池的“回收间隔”设置为更高的值(最大 1740 分钟)时,问题就会消失。然而,我希望“会话”(因为没有更好的名称)在应用程序池和应用程序池回收之间保持持久。

我做错了什么,我需要进行哪些更改才能使其正常工作?

持续时间:

  • IdentityTokenLifetime:300s / 5m
  • IdentityAccessToken:300s / 5m
  • 授权码寿命:300s / 5m
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    string connectionString = _config.GetValue<string>("ConnectionStrings:IdentityServerDBConnectionString");
    var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
    
    services.AddDbContext<IdentityServerDBContext>(x => x.UseSqlServer(connectionString));

    var builder = services.AddIdentityServer(
        options => {
            options.Authentication.CookieLifetime = TimeSpan.FromDays(14);  // As test
        }
    )
        .AddSigningCredential(LoadCertificate())
        .AddConfigurationStore(options =>
        {
           options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
               sql => sql.MigrationsAssembly(migrationsAssembly));
        })
        .AddOperationalStore(options =>
        {
           options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
               sql => sql.MigrationsAssembly(migrationsAssembly));
        })
        .AddProfileService<ProfileService>();

    // Custom implementations
    services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();
    services.AddTransient<IProfileService, ProfileService>();

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
       .AddCookie(o =>
       {
           o.SlidingExpiration = false;
           o.ExpireTimeSpan = TimeSpan.FromDays(14);  // As test
       });

    services.AddAuthorization();
}

*编辑: 正如 Tore 在下面的评论中指出的那样,缺少 DataProtection 实现是问题的原因。

使用他分享的链接,我能够通过添加 Microsoft.AspNetCore.DataProtection 包并将以下 sn-p 添加到 Startup 来解决它:

// Persistent data protection
services
    .AddDataProtection()
    .PersistKeysToDbContext<DBContext>();

【问题讨论】:

    标签: c# session identityserver4 persistent


    【解决方案1】:

    cookie 使用 ASP.NET Core 中的数据保护 API 进行加密,对于生产来说,正确配置它是明智之举,因此加密密钥/密钥环会保留在您的 Web 应用程序之外。

    我在这里写过关于数据保护 API 的博客:

    另见这些链接:

    【讨论】:

    • 另外,IIS 默认应用程序池设置很愚蠢 - 至少更改这些设置,以便它在一天中可预测的时间(甚至根本不)回收。确保您的数据保护和签名密钥在共享存储中是关键。除了上述内容,本文还涵盖了要考虑的各个方面:docs.identityserver.io/en/latest/topics/deployment.html
    • 这确实解决了我遇到的问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多