没有身份的Asp.net身份验证不会持久

时间:2018-02-16 10:15:01

标签: c# asp.net-core

我正在尝试为我的aspnet core 2.0网站实现登录表单。 我设置了14天的持久性,但30分钟后,Identity.User.IsAuthenticathed属性返回False

我的statup类:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            options.Cookie.SameSite = SameSiteMode.Lax;
            options.SlidingExpiration = true;
            options.ExpireTimeSpan = TimeSpan.FromDays(14);
        });

    var servConfiguration = Configuration.GetSection("ServConfiguration");
    services.Configure<ServConfigurationModel>(servConfiguration);
    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseStaticFiles();
    app.UseAuthentication();

    app.UseCookiePolicy(new CookiePolicyOptions()
    {
        MinimumSameSitePolicy = SameSiteMode.Lax,
        HttpOnly = HttpOnlyPolicy.Always,
        Secure = CookieSecurePolicy.Always
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

我的登录方式:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login([FromForm] LoginModel loginData)
    {
        if (!ModelState.IsValid)
        {
            logger.LogWarning("invalid login data username: " + "Username: " + loginData.Username);
            return View();
        }

        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, loginData.Username)
        };

        var claimsIdentity = new ClaimsIdentity(
            claims,
            CookieAuthenticationDefaults.AuthenticationScheme);

        var principal = new ClaimsPrincipal(claimsIdentity);
        await HttpContext.SignInAsync(principal, new AuthenticationProperties()
        {
            IsPersistent = true,
            AllowRefresh = true
        });
    }

我的登录检查

    [HttpGet]
    public async Task<IActionResult> LoginCheck()
    {
        if (User.Identity.IsAuthenticated)
        {
            logger.LogInformation("user is authenticated");
        }
        else
        {
            logger.LogInformation("user is not authenticated");
        }
        return View();
    }

请注意:aspnet cookie有正确的过期,但是如果我在网站上返回30分钟后用户仍然没有登录。

1 个答案:

答案 0 :(得分:0)

我解决了在iis常规设置上设置固定机器密钥的问题。

机器密钥用于加密,解密和验证表单身份验证数据和视图状态数据以及进程外会话状态识别的算法和密钥。

如果每次重启都自动生成机器密钥(默认),则会生成一个新密钥,然后尽管会话cookie存在,但由于密钥已更改,因此它仍然无效。

IIS Settings - Machine key