首页 > 解决方案 > SignInWithClaimsAsync 中的声明永久到期

问题描述

我正在使用带有 Identity 的 ASP.NET Core 3.1,并使用以下代码在声明中存储一些基本用户信息,例如他们的全名(我知道检查密码和其他内容,为简洁起见忽略它)

var user = await _userManager.FindByNameAsync(Input.Username);
var claims = new List<Claim>
{
    new Claim("UserFullname", user.Fullname, ClaimValueTypes.String)
}
await _signInManager.SignInWithClaimsAsync(user, Input.RememberMe, claims);

我正在_Layout.cshtml使用以下行访问它:

var userFullname = User.Claims.Single(c => c.Type == "UserFullname").Value;

问题是,即使用户仍然登录,这似乎会在一段时间内过期。我希望这在用户注销之前是永久的。

我确信必须有某种方法startup.cs来控制这一点,并且尽可能避免覆盖任何东西。

--EDIT--
正如@yinqiu 回答的评论中提到的,我使用以下行尝试了cookie身份验证方案:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);

但这也无济于事。

标签: asp.net-coreasp.net-identity

解决方案


我认为您可以尝试覆盖该SignInWithClaimsAsync方法。

public override async Task SignInWithClaimsAsync(ApplicationUser user, AuthenticationProperties authenticationProperties, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> additionalClaims)
{
    if (authenticationProperties != null && authenticationProperties.IsPersistent)
    {
        authenticationProperties.ExpiresUtc = DateTimeOffset.UtcNow.AddYears(1);
    }

    await base.SignInWithClaimsAsync(user, authenticationProperties, additionalClaims);
}

推荐阅读