Auth0 Home Blog Docs

How do I add a default role to a new user on first login?

Question: How do I assign a default role to a new user on first login?

Answer:
If you are using the Authorization Core, you can leverage the Management API in a rule to assign a role based on login count.

Example Rule:

function (user, context, callback) {
    var request = require("request");

    var count = context.stats && context.stats.loginsCount ? context.stats.loginsCount : 0;
    if (count > 1) {
        return callback(null, user, context);
    }

    var headers = {
        'Authorization': 'Bearer ' + auth0.accessToken,
    };
    const data = {
        "roles": [
            "[role id]"
        ]
    };

    request.post({
        url: `https://${auth0.domain}/api/v2/users/${user.user_id}/roles`,
        headers: headers,
        json: data
    }, (err, response, body) => {
        return callback(new Error("Can not update users with role"));
    });

    callback(null, user, context);
}

Supporting Documentation: