samneric
samneric

Reputation: 3218

OpenIddict Samples - Add 'unique-name' to the id_token

I am playing around with the RefreshFlow sample of OpenIddict-Samples. It works great. I notice in the Angular models there is a ProfileModel that is populated from the JWT_Decode of the id_token:

export interface ProfileModel {
sub: string;
jti: string;
useage: string;
at_hash: string;
nbf: number;
exp: number;
iat: number;
iss: string;

unique_name: string;
email_confirmed: boolean;
role: string[];

}

I can't see where on the server the unique_name is being populated. I have a requirement for this field and tried applying the value here:

        [HttpPost("~/connect/token"), Produces("application/json")]
    public async Task<IActionResult> Exchange([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request)
    {
        if (request.IsPasswordGrantType())
        {
            var user = await _userManager.FindByNameAsync(request.Username);
            if (user == null)
            {
                return BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "The username/password couple is invalid."
                });
            }

            // Validate the username/password parameters and ensure the account is not locked out.
            var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, lockoutOnFailure: true);
            if (!result.Succeeded)
            {
                return BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "The username/password couple is invalid."
                });
            }

            var properties = new AuthenticationProperties(new Dictionary<string, string>
            {
                { "unique_name", "hello World!" }
            });

            // Create a new authentication ticket.
            var ticket = await CreateTicketAsync(request, user, properties);

            return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
        }

Is this where I need to add it? I previously rolled my own token creator using JwtSecureDataFormat : ISecureDataFormat and added the field as a property.

How can I add it with OpenIddict/ASOS?

Thanks!

Upvotes: 2

Views: 1249

Answers (1)

samneric
samneric

Reputation: 3218

So I figured out how to achieve mostly what I wanted!!

I really didn't need to specifically add 'unique_name' to the token but simply add more claims than what the standard Identity framework adds for you.

This is how I did it:

Create a custom SignInManager:

public class OpenIdictSignInManager<TUser> : SignInManager<TUser> where TUser : IdentityUser
{
    public OpenIdictSignInManager(
        UserManager<TUser> userManager,
        IHttpContextAccessor contextAccessor,
        IUserClaimsPrincipalFactory<TUser> claimsFactory,
        IOptions<IdentityOptions> optionsAccessor,
        ILogger<SignInManager<TUser>> logger,
        IAuthenticationSchemeProvider schemes) : base(userManager,
                                                        contextAccessor, 
                                                        claimsFactory, 
                                                        optionsAccessor, 
                                                        logger, 
                                                        schemes)
    {
    }

    public override async Task<ClaimsPrincipal> CreateUserPrincipalAsync(TUser user)
    {
        var principal = await base.CreateUserPrincipalAsync(user);

        var identity = (ClaimsIdentity)principal.Identity;

        identity.AddClaim(new Claim(OpenIdConnectConstants.Claims.EmailVerified, user.EmailConfirmed.ToString().ToLower()));

        return principal;
    }
}

Then applied the new SignInManager to the startup.cs configuration:

        // Register the Identity services.
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddSignInManager<OpenIdictSignInManager<ApplicationUser>>();

Then added a claim destination when creating the ticket in AuthorizationController:

        // Note: by default, claims are NOT automatically included in the access and identity tokens.
        // To allow OpenIddict to serialize them, you must attach them a destination, that specifies
        // whether they should be included in access tokens, in identity tokens or in both.
        foreach (var claim in ticket.Principal.Claims)
        {
            // Never include the security stamp in the access and identity tokens, as it's a secret value.
            if (claim.Type == _identityOptions.Value.ClaimsIdentity.SecurityStampClaimType)
            {
                continue;
            }

            var destinations = new List<string>();

            // Identity Token destinations only
            if (new List<string>
            {
                OpenIdConnectConstants.Claims.EmailVerified
            }.Contains(claim.Type))
            {
                destinations.Add(OpenIdConnectConstants.Destinations.IdentityToken);
                claim.SetDestinations(destinations);
                continue;
            }

            destinations.Add(OpenIdConnectConstants.Destinations.AccessToken);

            // Only add the iterated claim to the id_token if the corresponding scope was granted to the client application.
            // The other claims will only be added to the access_token, which is encrypted when using the default format.
            if ((claim.Type == OpenIdConnectConstants.Claims.Name && ticket.HasScope(OpenIdConnectConstants.Scopes.Profile)) ||
                (claim.Type == OpenIdConnectConstants.Claims.Email && ticket.HasScope(OpenIdConnectConstants.Scopes.Email)) ||
                (claim.Type == OpenIdConnectConstants.Claims.Role && ticket.HasScope(OpenIddictConstants.Claims.Roles)))
            {
                destinations.Add(OpenIdConnectConstants.Destinations.IdentityToken);
            }

            claim.SetDestinations(destinations);
        }

It took me a few days of digging through code and googling to come up with this approach so I thought I'd share and hope it helps someone else out :)

Upvotes: 2

Related Questions