How can I add custom claims to be returned when requesting a token using OpenIddict?

蹲街弑〆低调 提交于 2019-12-06 14:32:08

What I need is to not only return the claims serialized in the access_token but to return them in the response like this:

While I encourage you to store these claims in identity tokens - so that they can be easily read by the client in a completely standard way, it's possible in OpenIddict 1.0 and 2.0 RTM. For that, you have 2 options:

Using a special "public" property (in your authorization controller, where authentication tickets are created):

ticket.SetProperty("custom_claim" + OpenIddictConstants.PropertyTypes.String, user.Id);

Note: OpenIddictConstants.PropertyTypes.String is a special suffix indicating the authentication property added to the ticket can be exposed as part of the token response. Other constants are available if you prefer returning your claim as a JSON number or a more complex JSON structure.

Using the events model (in Startup.cs):

services.AddOpenIddict()

    // Register the OpenIddict core services.
    .AddCore(options =>
    {
        // ...
    })

    // Register the OpenIddict server handler.
    .AddServer(options =>
    {
        // ...

        options.AddEventHandler<OpenIddictServerEvents.ApplyTokenResponse>(
            notification =>
            {
                if (string.IsNullOrEmpty(notification.Context.Error))
                {
                    var principal = notification.Context.Ticket.Principal;
                    var response = notification.Context.Response;
                    response["custom_claim"] = principal.FindFirst("your_claim_attached_to_the_principal").Value;
                }

                return Task.FromResult(OpenIddictServerEventState.Unhandled);
            });
    })

    // Register the OpenIddict validation handler.
    .AddValidation();

Well, we did it by using the Events property of the OpenIdConnectOptions in the Configure method of the Startup class when you add the Open Id Connect middleware, like this for instance:

            Events = new OpenIdConnectEvents
            {
                OnTicketReceived = n =>
                {
                    //TODO Your logic here to add custom claims via n.Principal.Identities.First().AddClaims();

                    return Task.CompletedTask;
                }
            }

Is that an option for your use case?

As an answer from @Pinpoint in his repository of openiddict-samples I followed this article (in the Implementing the Connect/Token Endpoint section)..
I figured out from his answer that what I'm trying to do is not standard, that's why it's not so obvious and easy to do.
You need to use JWT and add the custom claims to it so that the client can decode it and get the claims, not send them through the response it self.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!