Do you mind sharing your exact Action code here so we can take a look and see what might be the issue? Iād like to try and reproduce it as closely as possible.
This is a bit trickier than I expected given a couple things:
Post registration actions do not have access to the event.authorization object and therefore this needs to be broken out into a Post-login action.
Youāll need to introduce login into the Post-login action in order to account for the fact that you want to include the event.secrets.defaultRole if itās the userās first login and event.authorization.roles if itās any subsequent login. The reason being the role assigned in the Post-registration action will not be available via event.authorization.roles on first login.
Hereās a Post-registration and Post-login action that in unison are working for me:
Post User Registration:
exports.onExecutePostUserRegistration = async (event, api) => {
const namespace = "https://myappname.us.auth0.com";
const ManagementClient = require("auth0").ManagementClient;
const management = new ManagementClient({
domain: event.secrets.domain,
clientId: event.secrets.clientID,
clientSecret: event.secrets.clientSecret,
scope: "read:roles create:roles update:roles"
});
const params = { id : event.user.user_id};
var data = { "roles" : ['your_default_role_id']};
management.assignRolestoUser(params, data, function (err) {
if (err) {
// Handle error.
console.log(err)
}
console.log(`User ${event.user.email} successfully assigned default role.`)
// User assigned roles.
});
};
Post Login:
exports.onExecutePostLogin = async (event, api) => {
const namespace = "https://example.com"
//if this is the users first login, use the role hardcoded in event.secrets.defaultRole
if (event.stats.logins_count == 1) {
api.accessToken.setCustomClaim(`${namespace}/roles`, event.secrets.defaultRole ),
api.idToken.setCustomClaim(`${namespace}/roles`, event.secrets.defaultRole )
} else {
//if this isn't the users first login, assign roles from event.authorization.
if (event.authorization) {
console.log(event.stats.logins_count)
api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles ),
api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles )
}
}
};
Hey @AdmiralBot - That error looks to be related to a Post User Registration Hook as opposed to a Post User Registration Action. Are you able to confirm whether or not thatās the case?
Youāll need to add defaultRole to the actions events.secrets in order to resolve these errors - This is required for an initial login by a user as the role is not yet available in event.authorization.roles.
In this example, I am just using the string defaultRole role in event.secrets and adding it as a custom claim to tokens for the userās first login only. Once a user logs in again, the defaultRole is added via event.authorization.roles - Using the defaultRole via event.secrets is acting as a sort of placeholder in order to have the role in tokens on first login.