Reputation: 4164
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.
Upvotes: 5
Views: 4299
Reputation: 42010
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:
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.
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();
Upvotes: 4