In a single page JS app, we are calling a .NET Core WebAPI backend and passing the authorisation token. Within the WebAPI controller method we can retrieve the userId by calling:
In the User.Claims property there are 7 items, of this is “scope: openid profile email” however none of the claims contain the username or email. How can we add / access this?
There’s a few things to consider here, in particular:
username is not a standard OIDC claim so for a flow that is conformant to OIDC the username attribute won’t be automatically included neither in an ID token nor in the /userinfo response (Final: OpenID Connect Core 1.0 incorporating errata set 1).
in the scenario you described you likely are performing an OIDC authentication request and an OAuth 2.0 authorization request for your custom API (audience parameter) at the same time. In other words, you likely received an ID token and an access token.
The ID token is where user information will be automatically included as claims due to the scopes the application specified. Given you asked for the email scope then you’ll find the email information in the ID token as long as the end-user has that information.
The access token is meant to allow the application to call the API specified as part of the audience parameter on behalf of the end-user. At this time, an access token issued by Auth0 for this purpose will also be a JWT like it is the case for an ID token, however, the access token won’t automatically include any OIDC claims due to requested scopes.
If your API is using RS256 then the issued access token will have multiple audiences (aud) and one will be your API and the other the /userinfo endpoint. This technically allows the API to call that endpoint and get the same user information that was included in the ID token shared to the application. Given the inclusion of the email scope, the response from that endpoint would indeed return email information.
However, the above now requires an additional network request at the API level so you may want to review if explicitly including the required information in the access token as custom claims presents a better solution to your scenario. You can include namespaced custom claims in issued access tokens through the use of rules (Sample Use Cases: Scopes and Claims).
Given username is not a standard claim, if you want to include that information in an ID token you will require a custom claim or map that to a standard claim.