OpenIddict示例-在id_token中添加“唯一名称”

时间:2019-06-24 20:45:16

标签: asp.net-core openiddict

我正在玩OpenIddict-Samples的RefreshFlow示例。效果很好。我注意到在Angular模型中,有一个ProfileModel是从id_token的JWT_Decode填充的:

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[];

}

我看不到唯一名称在服务器上的哪个位置。我对此字段有要求,并尝试在此处应用值:

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

这是我需要添加它的地方吗?之前,我使用JwtSecureDataFormat:ISecureDataFormat滚动了自己的令牌创建者,并将该字段添加为属性。

如何使用OpenIddict / ASOS添加它?

谢谢!

1 个答案:

答案 0 :(得分:0)

所以我想出了主要如何实现我想要的东西!

我真的不需要在令牌中专门添加“ unique_name”,而只需添加比标准Identity框架为您添加的声明更多的声明即可。

这是我的方法:

创建自定义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;
    }
}

然后将新的SignInManager应用于startup.cs配置:

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

然后在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);
        }

我花了几天的时间来研究代码并进行谷歌搜索以提出这种方法,所以我想与大家分享并希望它可以帮助其他人:)