Search code examples
reactjsazuresingle-sign-onrolesuser-roles

React App using Microsoft SSO for signing in but getting roles from seperate database


I am working on adding Microsoft SSO to my React app. I am following this tutorial that I found: https://www.m-sterspace.io/posts/role-auth-azure-react#24-replace-their-authjs-component

I have the sign in and sign out portions working. Now I am trying to figure out how to implement roles. In that tutorial he is pulling the role(s) from the initial acquireTokenSilent call. But from my research, we probably want to have the roles stored in a seperate custom database for our app because there could be several roles for each user. For instance, read:users and modify:categories, etc. I don't think roles like that can be in Azure AD.

So my question is how do I get those roles on the initial sign in call? I want to use them in the React code to determine what pages the user can and cannot access. Looking at that Auth.js component from that link above and specifically the setSession function:

setSession(idToken) {
        try {
            let roles = [];
            // I don't think we can use the roles from Microsoft, we have to get them from our own database
            if (idToken.claims.roles) {
                roles = idToken.claims.roles;
            }
            const user = {
                id: idToken.objectId,
                name: idToken.claims.name,
                email: idToken.preferredName || idToken.preferred_username,
                role: roles[0]
            };
            this.setState({
                authenticated: true,
                idToken: idToken.rawIdToken, //this is the raw token that you want to pass to as your Bearer token.
                user: user,
                roles: []
            });
        } catch (e) {
            var aux = e.stack.split('\n');
            aux.splice(0, 2); //removing the line that we force to generate the error (var err = new Error();) from the message
            aux = aux.join('\n"');
            console.log(e + ' \n' + aux);
        }
    }

I am guessing that I would make an api call to my database in that code chunk up at the top where he sets the roles from the token claims. Would that work? Does that make sense? Do I need to go about this another way?


Solution

  • It is entirely possible to have application specific custom roles in Azure AD (known as Azure AD App Roles). You would need to define these roles in your Azure AD application and then assign users one or more of these app roles.

    When you acquire an access token for the application, these roles are included in the token (in roles or role claim).

    Please see this link for more details: https://learn.microsoft.com/en-us/entra/identity-platform/howto-add-app-roles-in-apps.