如何更改“.AspNetCore.Identity.Application”cookie 过期时间?

zde*_*dev 5 authentication asp.net-identity openid-connect asp.net-core identityserver4

我使用ASP.NET核心与Identity Server和Open标识连接所描述这里。设置“记住我”选项时(默认为 14 天),我需要更改身份验证 cookie 的过期时间。我可以看到名为“.AspNetCore.Identity.Application”的 cookie 对此负责。我正在尝试像这样设置到期时间:

.AddCookie(options =>
{
    options.Cookie.Expiration = TimeSpan.FromDays(1);
    options.ExpireTimeSpan = TimeSpan.FromDays(1);
})
Run Code Online (Sandbox Code Playgroud)

但它会影响另一个名为“.AspNetCore.Cookies”(包含相同的令牌值)的 cookie,它具有 Session 过期时间并且似乎没有做任何事情。我发现的所有更改过期时间的方法都只修改了“.AspNetCore.Cookies”cookie,我找不到任何修改“.AspNetCore.Identity.Application”cookie 的方法。(顺便说一句,services.ConfigureApplicationCookie某种原因,我根本没有触发方法)。

谁能解释一下这两个 cookie 之间的区别,以及如何修改“.AspNetCore.Identity.Application”过期时间?

我的代码 Startup.ConfigureServices

services.AddMvc(options =>
{
    // ...
})

services.AddAuthorization(options =>
{
    options.AddPolicy(PolicyNames.UserPolicy, policyBuilder =>
    {
        // ... 
    });
});

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie(options =>
{
    options.AccessDeniedPath = "/AccessDenied";
    options.SlidingExpiration = true;
})
.AddOpenIdConnect("oidc", options =>
{
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.Authority = "<authority>";
    options.RequireHttpsMetadata = false;
    options.ClientId = "<id>";
    options.ClientSecret = "<secret>";
    options.ResponseType = "code id_token";
    options.SaveTokens = true;
    options.GetClaimsFromUserInfoEndpoint = true;
    // ...
});

services.ConfigureApplicationCookie(options =>
{
    options.Cookie.Name = "MyCookie";
    options.Cookie.Expiration = TimeSpan.FromDays(1);
    options.ExpireTimeSpan = TimeSpan.FromDays(1);
});
Run Code Online (Sandbox Code Playgroud)

Jac*_* Ng 7

在浏览了两个AspNetCore 3.1&IdentityServer 4.0.4存储库之后,我找到了设置默认身份验证 cookie 选项的工作方法。

TD;LR:

    // in Startup.ConfigureService(IServiceCollection services)
    services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, option =>
    {
        option.Cookie.Name = "Hello"; // change cookie name
        option.ExpireTimeSpan = TimeSpan.FromSeconds(30); // change cookie expire time span
    });
Run Code Online (Sandbox Code Playgroud)

完整设置:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddRazorPages();

        // cookie policy to deal with temporary browser incompatibilities
        services.AddSameSiteCookiePolicy();
        services.AddDefaultAllowAllCors();

        // setting up dbcontext for stores;
        services.AddDbContext<ApplicationDbContext>(ConfigureDbContext);

        services
            .AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.SignIn.RequireConfirmedAccount = true;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

        // read clients from /sf/answers/3842467331/
        var builder = services.AddIdentityServer(options =>
        {
            options.Events.RaiseSuccessEvents = true;
            options.Events.RaiseFailureEvents = true;
            options.Events.RaiseErrorEvents = true;
            options.Events.RaiseInformationEvents = true;
            options.UserInteraction.LoginUrl = "/identity/account/login";
            options.IssuerUri = _configuration.GetValue<string>("IdentityServer:IssuerUri");
        })

            .AddAspNetIdentity<ApplicationUser>()
            .AddDeveloperSigningCredential()
            .AddConfigurationStore<ApplicationConfigurationDbContext>(option => option.ConfigureDbContext = ConfigureDbContext)
            .AddOperationalStore<ApplicationPersistedGrantDbContext>(option => { option.ConfigureDbContext = ConfigureDbContext; })
            .AddJwtBearerClientAuthentication()
            .AddProfileService<ApplicationUserProfileService>();

        services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, option =>
        {
            option.Cookie.Name = "Hello";
            option.ExpireTimeSpan = TimeSpan.FromSeconds(30);
        });
        services.AddScoped<Microsoft.AspNetCore.Identity.UI.Services.IEmailSender, EmailSender>();
        services.Configure<SmsOption>(_configuration);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // use this for persisted grants store
        InitializeDatabase(app);

        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseDefaultAllowAllCors();

        app.UseStaticFiles();

        app.UseRouting();

        app.UseIdentityServer();

        app.UseAuthorization();


        app.UseStatusCodePages(async context =>

        {
            var response = context.HttpContext.Response;

            if (response.StatusCode == StatusCodes.Status401Unauthorized ||
                response.StatusCode == StatusCodes.Status403Forbidden)
                response.Redirect("/identity/account/login");

            if (context.HttpContext.Request.Method == "Get" && response.StatusCode == StatusCodes.Status404NotFound)
            {
                response.Redirect("/index");
            }
        });

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            endpoints.MapRazorPages();
        });
    }
Run Code Online (Sandbox Code Playgroud)


sev*_*nmy 5

正如 Kirk Larkin 所说,“.AspNetCore.Identity.Application”cookie 可能是由使用 Asp.Net Identity 的 Identity Server 应用程序设置的。因此,如果您想在 IS4 应用程序上管理用户会话,则需要在那里对其进行配置。

IS4 应用程序:“.AspNetCore.Identity.Application”cookie。

如果您使用 Identity 将 cookie 配置为持久性,您需要在用户登录时设置过期时间。

var props = new AuthenticationProperties {
  IsPersistent = true,
  ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
};
await HttpContext.SignInAsync(userId, userName, props);
Run Code Online (Sandbox Code Playgroud)

如果您未设置,IsPersistent=true则 cookie 具有会话生存期,您可以像这样设置包含的身份验证票证到期时间:

.AddCookie(options => {
    options.Cookie.Name = "idsrv_identity";
    options.ExpireTimeSpan = TimeSpan.FromHours(8);
    options.SlidingExpiration = true;
  });
Run Code Online (Sandbox Code Playgroud)

您的客户端应用程序::“.AspNetCore.Cookies”cookie。

services.ConfigureApplicationCookie不被调用,因为如果你使用.AddCookie(...)this 优先。选项是一样的。

这将应用程序 cookie 设置为session

.AddCookie(options => {
    options.Cookie.Name = "myappcookie";
    options.ExpireTimeSpan = TimeSpan.FromHours(8);
    options.SlidingExpiration = true;
  });
Run Code Online (Sandbox Code Playgroud)

使用 OIDC 使应用程序 cookie 持久化的一种方法是OnSigningInAddCookie事件中设置过期时间

options.Events.OnSigningIn = (context) =>
{
    context.CookieOptions.Expires = DateTimeOffset.UtcNow.AddDays(30);
    return Task.CompletedTask;
};
Run Code Online (Sandbox Code Playgroud)

关于用户会话的说明。

每种情况都不同,因此没有最佳解决方案,但请记住,您必须处理两个用户会话。一个在 IS4 应用程序上,一个在您的客户端应用程序上。这些可能会不同步。您需要考虑客户端应用程序上的持久用户会话是否有意义。当中央 SSO(单点登录)会话过期时,您不希望您的用户保持登录您的客户端应用程序。