We are facing a specific scenario in the application where we have to add custom information to an access token. I have read the documents that i could find where we can add using Actions and Rules. I was able to add some basic information like email and user_id to the access tokens
For eg:
function addEmailToAccessToken(user, context, callback) {
// This rule adds the authenticated user’s email address to the access token.
var namespace = ‘http://example.com/’;
context.accessToken[namespace + ‘email’] = user.email;
context.accessToken[namespace + ‘id’] = user.identities[0].user_id;
return callback(null, user, context);
}
In Actions too i can do the same by adding an action to post login flow. The question i have is how to add custom information to access token.
Below is the use case scenario.
- We have build a login using custom login with Resource owner password flow.
- The front end calls the back-end and the back-end calls Auth0 (https://dev-xxxxxxxx.auth0.com/oauth/token) with email and password to get access toekns.
- In Auth0 i have a custom database configured. Therefore all the information is stored in the custom database.
Note: To accommodate some custom information during registration of a user [
api/v2/users] i have used user_metadata to include information like city province …etc as part of the request. - I have enable password grant in Auth0 and i have also made sure that it is password grant by checking the token in https://jwt.io/
- Next i have added a rule with “add email to access token default template”. I was also able to add user_id to the access token.
function addEmailToAccessToken(user, context, callback) {
var namespace = ‘https://example.com/’;
context.accessToken[namespace + ‘email’] = user.email;
context.accessToken[namespace + ‘id’] = user.identities[0].user_id;
return callback(null, user, context);
}
Blockquote
- I printed the user object and i received the following information
{
_id: ‘ac48cb434c56779ef4509658e965a468’,
clientID: ‘xxxxxx’,
created_at: ‘2022-12-05T08:28:21.414Z’,
email: ‘abc@gmail.com’,
identities: [
{
user_id: ‘1’,
provider: ‘auth0’,
connection: ‘xxx’,
isSocial: false
}
],
name: ‘abc@gmail.com’,
nickname: ‘abc’,
picture: ‘https://s.gravatar.com/avatar/565320b54542ab6c0b9cd9aa84847103?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fwa.png’,
updated_at: ‘2022-12-05T17:26:37.179Z’,
user_id: ‘auth0|1’,
global_client_id: xxxxx,
persistent: {}
}
- My question is how would i add some custom information to the above payload so that i can add it to the access token. In my case i would want to add role, organisation Id.
Note: Alternatively i can add the custom information as part of a cookie that i send to the front-end, but i would prefer to put it in access tokens.
Any help is appreciated or just point to a correct way of implementing it.