How to add additional claims to be included within the token?
As soon as the API receives the bearer token, the User.Identity object gets populated with the following claims.
[
{
"key": "nbf",
"value": "1484614344"
},
{
"key": "exp",
"value": "1484615244"
},
{
"key": "iss",
"value": "http://localhost:85"
},
{
"key": "aud",
"value": "http://localhost:85/resources"
},
{
"key": "aud",
"value": "WebAPI"
},
{
"key": "client_id",
"value": "MyClient"
},
{
"key": "sub",
"value": "d74c815a-7ed3-4671-b4e4-faceb0854bf6"
},
{
"key": "auth_time",
"value": "1484611732"
},
{
"key": "idp",
"value": "local"
},
{
"key": "role",
"value": "AccountsManager"
},
{
"key": "scope",
"value": "openid"
},
{
"key": "scope",
"value": "profile"
},
{
"key": "scope",
"value": "roles"
},
{
"key": "scope",
"value": "WebAPI"
},
{
"key": "scope",
"value": "offline_access"
},
{
"key": "amr",
"value": "pwd"
}
]
I want additional claims like username, email, legacySystemUserId
, etc. These fields already exist in the AspNetUsers
table (and doesn't repetitively exist in AspNetUserClaims
table) and are available in ASP .Net Core application in my ApplicationUser object.
I want them to be included in access token that is returned after authenticating with username and password. Want to use the same in my WebAPI application that doesn't have access to the identity-server database and its own database has data stored based on user's email address not the UserId (which is a guid generated in ASP .NET Identity and received as SUB claim).
I had been fighting this same issue for hours and finally pieced together the solution. This article was a big help, but to summarize and share my implementation:
In order to get the claims assigned to the user and attach them to the access token, you need to implement two interfaces on the identity server:
IResourceOwnerPasswordValidator
andIProfileService
. The following are my implementations of the two classes and are rough drafts, but they work.**Be sure to get the latest version of IdentityServer4 - 1.0.2 at this time.
and
Once you have those, they need to be added to your services in startup.cs:
Here is a quick look at my config:
After that, a call to the identity server from a client:
Inspect the token at jwt.io and see your results...