Last Updated: Jul 31, 2024
Overview
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.
Applies To
- Roles
- New User
Solution
Check out our video related to that topic:
When using the Authorization Core, leverage the Management API in a rule to assign a role based on login count.
Example Rule:
function (user, context, callback) {
const count = context.stats && context.stats.loginsCount ? context.stats.loginsCount : 0;
if (count > 1) {
return callback(null, user, context);
}
const ManagementClient = require('auth0@2.27.0').ManagementClient;
const management = new ManagementClient({
token: auth0.accessToken,
domain: auth0.domain
});
const params = { id : user.user_id};
const data = { "roles" : ["ROLE_ID_1","ROLE_ID_2"]};
management.users.assignRoles(params, data, function (err, userAssignedRoles) {
if (err) {
// Handle error.
console.log(err);
}
callback(null, user, context);
});
}
This can also 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 > Custom Actions to view the list of existing Actions.
- Select Build Custom.
- 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.users.assignRoles(params, data)
} catch (e) {
console.log(e)
// Handle error
}
};