Ivar
Ivar

Reputation: 1308

Add RememberMe value as Claim in JWT (Identity Server 4)

I'm using IdentityServer 4.

Is it possible to access the value of the RememberMe boolean when issuing claims? (named isPersistent in the Microsoft.AspNetCore.Identity)

My idea is to add a claim reflecting the RememberMe value so that other applications can use the value.

Currently I'm adding my Claims in the implementation of the interface 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);
 // ..            

Or can the RememberMe value be accessed by some other method?

Upvotes: 1

Views: 1026

Answers (2)

Semyon
Semyon

Reputation: 538

You can add additional claims during the user's login. There is an overload for SignInAsync which accepts an array of additional claims. Here is a code snippet.

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);

Please note that to make this solution work it's necessary to insert your claim name to the IdentityClaims table.

Upvotes: 2

Nan Yu
Nan Yu

Reputation: 27588

Yes , you should add claim to tokens . In standard OIDC specifications, token is the
bond between client and identity provider . The profile service is called whenever IdentityServer needs to return claims about a user to a client applications , and could be used to add your custom claims .

http://docs.identityserver.io/en/latest/reference/profileservice.html

Upvotes: 0

Related Questions