Add a Default Role to a New User on First Login
This article clarifies whether it is possible to add a default role to a new user on the first login. Users may need to be created with a specific role.
- Roles
- New User
- Action
This can be achieved in an Action with the following Post-Login Action code:
- Create an Application that will use the Action.
- Authorize it to the API created with the required scopes. See Enable Role-Based Access Control for APIs.
- Create an Auth0 Action.
To get an Action working in a specific flow, create the Action and then add it to a flow.
- Navigate to Auth0 Dashboard > Actions > Library to view the list of existing Actions.
- Select Create Action > Create Custom Action.
- Enter a Name and select the Login / Post Login trigger since an Action will be added to the Login flow.
- Then select Create.
- Store the application’s credentials in the Action’s event.secrets object.
Use the domain, client ID, and client secret in the application settings of the app created in step 1. See Add a dependency
- Add the auth0 npm module/ dependency.
- See Add a dependency.
NOTE: Use the latest version of the module, leave the Version textbox blank, click on any other part of the Add Dependency dialog box, and click on the Create button.
- Initialize and use the Management API in the Action.
Next, implement the code logic. The following sample code logic assigns a user a role based on their login count.
exports.onExecutePostLogin = async (event, api) => {
if (event.stats.logins_count !== 1) {
return;
}
const ManagementClient = require('auth0').ManagementClient;
const management = new ManagementClient({
domain: event.secrets.domain,
clientId: event.secrets.clientId,
clientSecret: event.secrets.clientSecret,
});
const params = { id : event.user.user_id};
const data = { "roles" : ["YOUR_ROLE_ID"]};
try {
const res = await management.assignRolestoUser(params, data)
} catch (e) {
console.log(e)
// Handle error
}
};