标签: cookie-authentication

如何使用.netcore 2.0身份和cookie身份验证正确设置会话超时

我正在尝试在asp.netcore 2.0 MVC应用程序中使用带有cookie身份验证的身份.我想将会话超时设置为150天,因此登录的用户不需要在很长一段时间内再次登录.我设置options.ExpireTimeSpan = TimeSpan.FromDays(150);但会话在几分钟后关闭,即使用户正在积极使用该应用程序.

我正在关注官方文档,我在Startup.cs上有这个:

ConfigureServices方法:

    services.AddIdentity<User, Role>()
            .AddDefaultTokenProviders();

    // Identity Services
    services.AddTransient<IUserStore<User>, UserService>();
    services.AddTransient<IRoleStore<Role>, RoleService>();

    services.Configure<IdentityOptions>(options =>
    {
        // Password settings
        options.Password.RequireDigit = false;
        options.Password.RequiredLength = 8;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = false;
        options.Password.RequireLowercase = false;
        options.Password.RequiredUniqueChars = 3;

        // Lockout settings
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
        options.Lockout.MaxFailedAccessAttempts = 10;
        options.Lockout.AllowedForNewUsers = true;

        // User settings
        options.User.RequireUniqueEmail = true;
    });

    services.ConfigureApplicationCookie(options =>
    {
        // Cookie settings
        options.Cookie.HttpOnly = true;                
        options.ExpireTimeSpan = TimeSpan.FromDays(150);
        options.LoginPath = "/User/Login"; 
        options.LogoutPath …
Run Code Online (Sandbox Code Playgroud)

session-timeout asp.net-identity asp.net-core-2.0 cookie-authentication

7
推荐指数
0
解决办法
8578
查看次数

为ConfigureApplicationCookie 设置自定义SessionStore,无需BuildServiceProvider()

我有一个 .NET Core 3 项目(最近从 2.2 升级),它使用 Redis 分布式缓存和 cookie 身份验证。

目前看起来是这样的:

public void ConfigureServices(IServiceCollection services)
{
    // Set up Redis distributed cache
    services.AddStackExchangeRedisCache(...);

    ...

    services.ConfigureApplicationCookie(options =>
    {
        ...
        // Get a service provider to get the distributed cache set up above
        var cache = services.BuildServiceProvider().GetService<IDistributedCache>();

         options.SessionStore = new MyCustomStore(cache, ...);
    }):
}
Run Code Online (Sandbox Code Playgroud)

问题是BuildServiceProvider()导致构建错误:

Startup.cs(...):警告 ASP0000:从应用程序代码调用“BuildServiceProvider”会导致创建单例服务的附加副本。考虑替代方案,例如依赖注入服务作为“配置”的参数。

这似乎不是一个选项 -ConfigureApplicationCookie位于Startup.ConfigureServices并且只能配置新服务,Startup.Configure可以使用新服务,但不能覆盖CookieAuthenticationOptions.SessionStore为我的自定义商店。

services.AddSingleton<ITicketStore>(p => new MyCustomRedisStore(cache, ...))我之前尝试过添加ConfigureApplicationCookie,但这被忽略了。

显式设置CookieAuthenticationOptions.SessionStore似乎是让它使用本地内存存储以外的任何内容的唯一方法。 …

dependency-injection stackexchange.redis .net-core asp.net-core cookie-authentication

7
推荐指数
2
解决办法
6607
查看次数

ASP.Net Core Cookie 身份验证不是持久的

我开始使用ASP.Net Core 2.2开发网站。我正在通过自定义 cookie 身份验证(而不是身份)实现登录/注销。

请查看或克隆repo

git clone https://github.com/mrmowji/aspcore-custom-cookie-authentication.git .
Run Code Online (Sandbox Code Playgroud)

...或阅读以下代码片段。

这里是代码Startup.cs

public void ConfigureServices(IServiceCollection services) {
  ...

  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => {
      options.LoginPath = new PathString("/login");
      options.ExpireTimeSpan = TimeSpan.FromDays(30);
      options.Cookie.Expiration = TimeSpan.FromDays(30);
      options.SlidingExpiration = true;
    });

  ...

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
  ...

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

  app.UseAuthentication();

  app.UseMvc(routes =>
  {
    ...
Run Code Online (Sandbox Code Playgroud)

这是Login操作代码:

public async Task<IActionResult> Login(LoginViewModel userToLogin) {
  var username = "username"; // just to test
  var password = "password"; …
Run Code Online (Sandbox Code Playgroud)

c# authentication asp.net-core cookie-authentication

4
推荐指数
1
解决办法
1696
查看次数

Cookie.ExpireTimeSpan 被忽略并在 CookieAuthentication 中设置为 Session

我有一个问题,而试图设置过期我一个cookie的时候CookieAuthentication,似乎ExpireTimeSpan只是忽略,当我得到在浏览器cookie的它的到期时间设置为Session..

我正在使用带有 .NET Core 3.1 的 c# 8.0,这是我的ConfigureService代码:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options => {
            options.Cookie.Name = "authToken";
            options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
            options.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = (context) =>
                {
                    context.HttpContext.Response.Redirect("https://example.com/test/expired.html");
                    return Task.CompletedTask;
                }
            };
        });
        services.AddControllers();
    }
Run Code Online (Sandbox Code Playgroud)

但这就是我得到它的方式

在此处输入图片说明

c# asp.net-web-api cookie-authentication

4
推荐指数
1
解决办法
1413
查看次数

ASP .Net Core,将 JWT 存储在 Cookie 中

我听说这是存储 JWT 最安全的方式之一。我的问题是。我怎样才能将它保存在cookie中?

这是Startup.cs中ConfigureServises中的函数

services.AddControllers();
        services.AddTransient<IUserRepository, UserRepository>();
        services.AddTransient<ITokenService, TokenService>();
        IdentityModelEventSource.ShowPII = true;
          services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
          {
              options.TokenValidationParameters = new TokenValidationParameters
              {
                  ValidateIssuer = true,
                  ValidateAudience = true,
                  ValidateLifetime = true,
                  ValidateIssuerSigningKey = true,
                  ValidIssuer = Configuration["Jwt:Issuer"],
                  ValidAudience = Configuration["Jwt:Issuer"],
                  IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
              };
          });
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-mvc jwt asp.net-core cookie-authentication

4
推荐指数
1
解决办法
5694
查看次数

应用程序池回收后CookieAuthentication cookie无效

我有一个使用 Microsoft.AspNetCore.Authentication (2.2.0) 的 .net core 项目,配置为使用 CookieAuthentication。Cookie 配置为持久性并在 7 天后过期。问题是每当应用程序池被回收时,所有登录的用户都会被注销。

我根本不使用会话。我已经验证该 cookie 仍然存在于网络浏览器中,看来现有的 cookie 被服务器确定为无效。我怎样才能改变这种行为?

这是当前的配置:

services
    .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(
        CookieAuthenticationDefaults.AuthenticationScheme,
        options =>
        {
            options.AccessDeniedPath = "/";
            options.LoginPath = "/";
            options.LogoutPath = "/Authentication/Logout";
            options.Events.OnRedirectToLogin = context =>
            {
                context.Response.Redirect("/?returnUrl=" + context.Request.GetEncodedPathAndQuery());

                return Task.CompletedTask;
            });
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc asp.net-core cookie-authentication

2
推荐指数
1
解决办法
1158
查看次数