为什么我的ASP.NetCore身份验证cookie无法让我保持登录状态?

问题描述 投票:0回答:1

我是AspNetCore,其中间件和身份的新手。我正在建立一个非常简单的网站,用户可以在该网站上登录,并可以检查通常的“记住我”复选框并保持登录状态。“记住我”不起作用,大约10到15分钟后,我被重定向到登录页面再次。我在浏览器中看到了cookie,并且它的有效期确实是我设置的日期:将来30天。我的代码如下。我觉得我想念什么,但我不知道。

我的Startup.cs类:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }

    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}").RequireAuthorization();

        endpoints.MapRazorPages();
    });
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool<ApplicationDbContext>(options => 
                                 options.UseSqlServer(Configuration.GetConnectionString("xxxx")));

    services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();

    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromDays(30);
        options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
        options.SlidingExpiration = true;
        options.LoginPath = "/account/login";
        options.LogoutPath = "/account/logout";
        options.AccessDeniedPath = "/account/accessdenied";
    });

    services.AddControllersWithViews();

    services.AddRazorPages();
}

我的AccountController登录方法:

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(model.EmailAddress, model.Password, 
                                                              model.RememberMe, false);

        if (result.Succeeded)
            return RedirectToAction("index", "links");

        ModelState.AddModelError(string.Empty, "Invalid login");
    }

        return View(model);
}

我在浏览器中的cookieenter image description here

asp.net-core asp.net-core-identity
1个回答
0
投票

经过数周的谷歌搜索,我终于在this post中找到了解决方法。您必须配置数据保护以使登录名保持不变。此解决方案还可以使用户在部署和IIS重新启动后保持登录状态。

我按照this post的建议将机器密钥添加到了web.config,然后将数据保护添加到了ConfigureServices方法...

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
            // This helps surviving a restart: a same app will find back its keys. Just ensure to create the folder.
            .PersistKeysToFileSystem(new DirectoryInfo("\\MyFolder\\keys\\"))
            // This helps surviving a site update: each app has its own store, building the site creates a new app
            .SetApplicationName("MyWebsite")
            .SetDefaultKeyLifetime(TimeSpan.FromDays(90));
}

阅读更多here

© www.soinside.com 2019 - 2024. All rights reserved.