Role based authorization in Angular with Azure AD and app roles
How to limit access to apps, routes and features in Angular by assigning users to app roles in Azure Active Directory
In this previous post I discussed how to authenticate users in Angular using the Microsoft authentication library (MSAL) and Azure Active Directory: https://medium.com/medialesson/authenticating-angular-apps-with-azure-active-directory-using-msal-angular-1-0-d7b2f4914be9
Authenticating users in an Angular app is usually just the first step to control and limit access in an app and to features. Now that we know who the users is and that the user is a member of our organization we want to decide whether to allow access to the app, certain areas or features of the app based on app roles.
One important drawback to consider: app roles are created individually per app registration. This means that in typical client server situations where we have a client (e.g. Angular) and a server/backend (e.g. Azure Functions) this means we need to create app roles in both app registrations and also manage user assignments for both separately. This can be mitigated by assigning app roles to security groups but this feature is limited to Azure AD premium tenants and so not available if an organization is using the Azure AD that comes with Microsoft 365.
Read more about app roles and other options for authorization here: https://docs.microsoft.com/de-de/azure/architecture/multitenant-identity/app-roles
Setup an app role
App roles are created in the app registration’s manifest and users can be assigned those roles. So let’s open our Angular app registration’s manifest in the Azure portal and add a role:
Note that each role needs a unique id and the value property is the value that will be included in the user’s claims.
Assign users to an app role
To assign users open the app registration by opening it via Enterprise applications instead of App registrations:
Switch to Users and groups and select Add user:
Select a user and note the selected role:
Access user’s role in Angular
Building on the Angular authentication sample created here https://medium.com/medialesson/authenticating-angular-apps-with-azure-active-directory-using-msal-angular-1-0-d7b2f4914be9 let’s output the user’s role in the profile component:
And bind it in the template:
This gives us an array of the values of a user:
Limit routes to roles
A common use case is to limit a route like settings to a role like the Admin role. This can be achieved by implementing a role guard.
This guard checks if there is an intersection between the user’s roles and the allowed roles provided in the route’s data property. To use this guard we also need to add the guard and a data property to our route config:
With app roles it’s just a few clicks to enable authorization in Angular!