首页 > 解决方案 > 在 JWT (Identity Server 4) 中添加 RememberMe 值作为声明

问题描述

我正在使用 IdentityServer 4。

RememberMe发出声明时是否可以访问布尔值?isPersistent(在 Microsoft.AspNetCore.Identity 中命名)

我的想法是添加一个反映该RememberMe值的声明,以便其他应用程序可以使用该值。

目前我正在接口的实现中添加我的声明IProfileService.GetProfileDataAsync

public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
    await Task.Run(() =>
    {
        try
        {
            var user = _userManager.GetUserAsync(context.Subject).Result;
            var claims = new List<Claim>
            {
                // I'm adding my current claims here, like so:
                new Claim("contact_id", user.ContactId.ToString()),
                // etc

                // I would like to add RememberMe
                new Claim("remember_me", ??? )
            };
            context.IssuedClaims.AddRange(claims);
 // ..            

还是可以RememberMe通过其他方法访问该值?

标签: asp.net-coreidentityserver4

解决方案


您可以在用户登录期间添加其他声明。SignInAsync有一个重载,它接受一系列附加声明。这是一个代码片段。

public async Task<IActionResult> Login(LoginInputModel model)
...
                AuthenticationProperties props = null;
                Claim keepMeLoggedIn = null;
                if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                {
                    props = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                    };
                    keepMeLoggedIn = new Claim(AccountOptions.KeepLoggedInClaim, true.ToString());

                }

                await HttpContext.SignInAsync(userId.ToString(), model.Username, props, keepMeLoggedIn);

请注意,要使此解决方案有效,必须将您的声明名称插入IdentityClaims表中。


推荐阅读