Add custom claims to token in Auth0
By default, the token of Auth0 does not contain any information about the user's name. The default claim for the name would be: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
.
In C#/.NET ClaimTypes.Name
represents this claim name. Therefore, if we tried to access the ClaimTypes.Name
claim in .NET without a custom Auth0 rule, the return value would be null
.
So that Auth0 inserts more than just the 10 standard claims into a token, a rule is needed.
Auth0 Rules
Auth0 Rules are hooks that take effect as soon as an event occurs. They are part of the Auth0 Authentication Pipeline.
Therefore it is possible to write your own rules, which can then become part of the pipeline and add information to the token.
Add rule
Rules can be created via the dashboard. Administrative rights are required.
There are a number of templates that simplify the creation of a rule. For simplicity I use an empty rule here.
Auth0 Rules always have a name and a corresponding script snippet based on a JavaScript function.
The name of a user in Auth0 is listed in the 'name' property, which we can access in the rule and assign to the claim.
function (user, context, callback) {
context.accessToken['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'] = user.name;
callback(null, user, context);
}
After saving, each new token now has an additional claim of the user's name.
However, if the user has no name in Auth0, the claim is in the token but has no value ;-)