5

Using ASP.NET Core with OpenIddict password grant.

When calling an authentication end point, I am getting this:

{
  "token_type": "Bearer",
  "access_token": "eyJhbGciOiJ...",
  "expires_in": 1800
}

How can I include the user id in the response? I can see it in the decoded token, but my user app will not be decoding it.

Adam
  • 3,872
  • 6
  • 36
  • 66

1 Answers1

4

How can I include the user id in the response?

Ideally, consider using the identity token - always a JWT by definition - returned by OpenIddict when you specify scope=openid.

Alternatively, you can also enable the userinfo endpoint and send a userinfo request to get back a sub claim containing the user identifier: http://openid.net/specs/openid-connect-core-1_0.html#UserInfo.

If you really prefer returning the user identifier as a token response property, you have two options:

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

ticket.SetProperty("user_id" + 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 identifier 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["user_id"] = principal.FindFirst(OpenIddictConstants.Claims.Subject).Value;
                }

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

    // Register the OpenIddict validation handler.
    .AddValidation();
Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131
  • I haven't tried as given all the friction I got, I decided it is too early to upgrade to .NET Core and it worth waiting a year or so. Thank you for the response anyway. – Adam Aug 22 '16 at 14:33
  • what is the replacement for `OpenIddictServerEventState` constants in 3+ versions? I was seeking for it a couple of days but have not found any info. – anatol Jul 11 '22 at 07:58