Angular single-page application calling .NET Core web API using Security Groups to implement Role-Based Access Control
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- More information
- Community Help and Support
- Contributing
This sample demonstrates a cross-platform application suite involving an Angular single-page application (TodoListSPA) calling an ASP.NET Core web API (TodoListAPI) secured with the Microsoft identity platform. In doing so, it implements Role-based Access Control (RBAC) by using Azure AD Security Groups.
Access control in Azure AD can also be done with App Roles, as shown in the previous tutorial. Groups and App Roles in Azure AD are by no means mutually exclusive - they can be used in tandem to provide even finer grained access control.
In the sample, a dashboard component allows signed-in users to see the tasks assigned to them or other users based on their memberships to one of the two security groups, GroupAdmin and GroupMember.
- The TodoListSPA uses MSAL Angular to authenticate a user with the Microsoft identity platform.
- The app then obtains an access token from Azure Active Directory (Azure AD) on behalf of the authenticated user for the TodoListAPI.
- TodoListAPI uses Microsoft.Identity.Web to protect its endpoint and accept only authorized calls.
| File/folder | Description |
|---|---|
SPA/src/app/auth-config.ts |
Authentication parameters for SPA project reside here. |
SPA/src/app/app.module.ts |
MSAL Angular is initialized here. |
SPA/src/app/group-guard.service.ts |
This service protects other components that require user to be in a group. |
SPA/src/app/graph.service.ts |
This service queries Microsoft Graph in case of groups overage. |
API/appsettings.json |
Authentication parameters for API project reside here. |
API/Startup.cs |
Microsoft.Identity.Web is initialized here. |
API/Utils/GraphHelper.cs |
Queries Microsoft Graph with Graph SDK in case groups overage occurs. |
- An Azure AD tenant. For more information see: How to get an Azure AD tenant
- At least two user accounts in your Azure AD tenant.
Using a command line interface such as VS Code integrated terminal, follow the steps below:
git clone https://github.com/Azure-Samples/ms-identity-javascript-angular-tutorial.gitor download and extract the repository .zip file.
⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.
cd ms-identity-javascript-angular-tutorial
cd 5-AccessControl/2-call-api-groups/API
dotnet restore dotnet dev-certs https --clean
dotnet dev-certs https --trustFor more information and potential issues, see: HTTPS in .NET Core.
cd ../
cd SPA
npm installThere are two projects in this sample. Each needs to be registered separately in your Azure AD tenant. To register these projects, you can:
- either follow the steps below for manual registration,
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
- modify the configuration files.
Expand this section if you want to use this automation:
-
On Windows, run PowerShell as Administrator and navigate to the root of the cloned directory
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Azure AD application and configure the code of the sample application accordingly.
-
In PowerShell run:
cd .\AppCreationScripts\ .\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
- Navigate to the Azure portal and select the Azure AD service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
msal-dotnet-api. - Under Supported account types, select Accounts in this organizational directory only.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- Select Save to save your changes.
- In the app's registration screen, select the Certificates & secrets blade in the left to open the page where we can generate secrets and upload certificates.
- In the Client secrets section, select New client secret:
- Type a key description (for instance
app secret), - Select one of the available key durations (In 1 year, In 2 years, or Never Expires) as per your security posture.
- The generated key value will be displayed when you select the Add button. Copy the generated value for use in the steps later.
- You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Azure portal before navigating to any other screen or blade.
- Type a key description (for instance
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
- Select the Add a permission button and then,
- Ensure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph
- In the Delegated permissions section, select the User.Read, GroupMember.Read.All in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- GroupMember.Read.All requires admin to consent. Select the Grant/revoke admin consent for {tenant} button, and then select Yes when you are asked if you want to grant consent for the requested permissions for all account in the tenant. You need to be an Azure AD tenant admin to do this.
- Select the Add a permission button and then,
- In the app's registration screen, select the Expose an API blade to the left to open the page where you can declare the parameters to expose this app as an API for which client applications can obtain access tokens for.
The first thing that we need to do is to declare the unique resource URI that the clients will be using to obtain access tokens for this Api. To declare an resource URI, follow the following steps:
- Select
Setnext to the Application ID URI to generate a URI that is unique for this app. - For this sample, accept the proposed Application ID URI (
api://{clientId}) by selecting Save.
- Select
- All APIs have to publish a minimum of one scope for the client's to obtain an access token successfully. To publish a scope, follow the following steps:
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- For Scope name, use
access_as_user. - Select Admins and users options for Who can consent?.
- For Admin consent display name type
Access msal-dotnet-api. - For Admin consent description type
Allows the app to access msal-dotnet-api as the signed-in user. - For User consent display name type
Access msal-dotnet-api. - For User consent description type
Allow the application to access msal-dotnet-api on your behalf. - Keep State as Enabled.
- Select the Add scope button on the bottom to save this scope.
- For Scope name, use
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- On the right side menu, select the
Manifestblade.- Set
accessTokenAcceptedVersionproperty to 2. - Click on Save.
- Set
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
API\appsettings.jsonfile. - Find the app key
Domainand replace the existing value with your Azure AD tenant name. - Find the app key
ClientIdand replace the existing value with the application ID (clientId) of themsal-dotnet-apiapplication copied from the Azure portal. - Find the app key
TenantIdand replace the existing value with your Azure AD tenant ID. - Find the app key
ClientSecretand replace the existing value with the key you saved during the creation of themsal-dotnet-apiapp, in the Azure portal.
- Navigate to the Azure portal and select the Azure AD service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
msal-angular-spa. - Under Supported account types, select Accounts in this organizational directory only.
- In the Redirect URI (optional) section, select Single-page application in the combo-box and enter the following redirect URI:
http://localhost:4200/.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- Select Save to save your changes.
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
- Select the Add a permission button and then:
- Ensure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph
- In the Delegated permissions section, select the User.Read, GroupMember.Read.All in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- GroupMember.Read.All requires admin to consent. Select the Grant/revoke admin consent for {tenant} button, and then select Yes when you are asked if you want to grant consent for the requested permissions for all account in the tenant. You need to be an Azure AD tenant admin to do this.
- Select the Add a permission button and then:
⚠️ The next step requires you to go back to your msal-dotnet-api registration.
- Now you need to leave the registration for msal-angular-spa and go back to your app registration for msal-dotnet-api.
- From the app's Overview page, select the Manifest section.
- Find the entry for
KnownClientApplications, and add the Application (client) ID of themsal-angular-spaapplication copied from the Azure portal. i.e.KnownClientApplications: [ "your_client_id_for_TodoListSPA" ]
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
SPA\src\app\app-config.tsfile. - Find the app key
clientIdand replace the existing value with the application ID (clientId) of the msal-angular-spa application copied from the Azure portal. - Find the app key
todoListApi.resourceUriand replace the existing value with the base address of the msal-dotnet-api project (by defaulthttps://localhost:44351/api/todolist). - Find the app key
todoListApi.resourceScopesand replace the existing value with Scope you created earlierapi://{clientId-of-service}/access_as_user.
You have two different options available to you on how you can further configure your application(s) to receive the groups claim.
- Receive all the groups that the signed-in user is assigned to in an Azure AD tenant, included nested groups.
- Receive the groups claim values from a filtered set of groups that your application is programmed to work with (Not available in the Azure AD Free edition).
To get the on-premise group's
samAccountNameorOn Premises Group Security Identifierinstead of Group ID, please refer to the document Configure group claims for applications with Azure Active Directory.
Configure your application to receive all the groups the signed-in user is assigned to, including nested groups
- In the app's registration screen, select the Token Configuration blade in the left to open the page where you can configure the claims provided tokens issued to your application.
- Select the Add groups claim button on top to open the Edit Groups Claim screen.
- Select
Security groupsor theAll groups (includes distribution lists but not groups assigned to the application)option. Choosing both negates the effect ofSecurity Groupsoption. - Under the ID section, select
Group ID. This will result in Azure AD sending the Object ID of the groups the user is assigned to in the groups claim of the ID Token that your app receives after signing-in a user.
Configure your application to receive the groups claim values from a filtered set of groups a user may be assigned to
- This option is useful when your application is interested in a selected set of groups that a signing-in user may be assigned to and not every security group this user is assigned to in the tenant. This option also saves your application from running into the overage issue.
- This feature is not available in the Azure AD Free edition.
- Nested group assignments are not available when this option is utilized.
- In the app's registration screen, select the Token Configuration blade in the left to open the page where you can configure the claims provided tokens issued to your application.
- Select the Add groups claim button on top to open the Edit Groups Claim screen.
- Select
Groups assigned to the application.- Choosing additional options like
Security GroupsorAll groups (includes distribution lists but not groups assigned to the application)will negate the benefits your app derives from choosing to use this option.
- Choosing additional options like
- Under the ID section, select
Group ID. This will result in Azure AD sending the Object ID of the groups the user is assigned to in thegroupsclaim of the ID Token that your app receives after signing-in a user. - If you are exposing a web API using the Expose an API option, then you can also choose the
Group IDoption under the Access section. This will result in Azure AD sending the Object ID of the groups the user is assigned to in thegroupsclaim of the Access Token issued to the client applications of your API. - In the app's registration screen, select on the Overview blade in the left to open the Application overview screen. Select the hyperlink with the name of your application in Managed application in local directory (note this field title can be truncated for instance
Managed application in ...). When you select this link you will navigate to the Enterprise Application Overview page associated with the service principal for your application in the tenant where you created it. You can navigate back to the app registration page by using the back button of your browser. - Select the Users and groups blade in the left to open the page where you can assign users and groups to your application.
- Select the Add user button on the top row.
- Select User and Groups from the resultant screen.
- Choose the groups that you want to assign to this application.
- Click Select in the bottom to finish selecting the groups.
- Select Assign to finish the group assignment process.
- Your application will now receive these selected groups in the
groupsclaim when a user signing in to your app is a member of one or more these assigned groups.
- Select the Properties blade in the left to open the page that lists the basic properties of your application.Set the User assignment required? flag to Yes.
💡 Important security tip
When you set User assignment required? to Yes, Azure AD will check that only users assigned to your application in the Users and groups blade are able to sign-in to your app. You can assign users directly or by assigning security groups they belong to.
⚠️ During Token Configuration, if you have chosen any other option except groupID (e.g. like DNSDomain\sAMAccountName) you should enter the group name (for examplecontoso.com\Test Group) instead of the object ID below:
- Open the
SPA\src\app\app-config.tsfile. - Find the app key
groups.groupAdminand replace the existing value with the object ID of the GroupAdmin group copied from the Azure portal. - Find the app key
groups.groupMemberand replace the existing value with the object ID of the GroupMember group copied from the Azure portal.
⚠️ During Token Configuration, if you have chosen any other option except groupID (e.g. like DNSDomain\sAMAccountName) you should enter the group name (for examplecontoso.com\Test Group) instead of the object ID below:
- Open the
API\appsettings.jsonfile. - Find the app key
Groups.GroupAdminand replace the existing value with the object ID of the GroupAdmin group copied from the Azure portal. - Find the app key
Groups.GroupMemberand replace the existing value with the object ID of the GroupMember group copied from the Azure portal.
Using a command line interface such as VS Code integrated terminal, locate the application directory. Then:
cd ../
cd msal-angular-spa
npm startIn a separate console window, execute the following commands:
cd msal-dotnet-api
dotnet run- Open your browser and navigate to
http://localhost:4200. - Sign-in using the button on top-right:
- Click on the Get My Tasks button to access your (the signed-in user's) todo list:
- If the signed-in user has the right privileges (i.e. in the right "group"), click on the See All Tasks button to access every users' todo list:
- If the signed-in user does not have the right privileges, clicking on the See All Tasks will give an error:
ℹ️ Consider taking a moment to share your experience with us
Much of the specifics of implementing RBAC with Security Groups is the same with implementing RBAC with App Roles discussed in Chapter1. In order to avoid redundancy, here we discuss particular issues that might arise with using groups claim.
To ensure that the token size doesn’t exceed HTTP header size limits, the Microsoft Identity Platform limits the number of object Ids that it includes in the groups claim.
If a user is member of more groups than the overage limit (150 for SAML tokens, 200 for JWT tokens, 6 for Single Page applications), then the Microsoft Identity Platform does not emit the group IDs in the groups claim in the token. Instead, it includes an overage claim in the token that indicates to the application to query the MS Graph API to retrieve the user’s group membership.
We strongly advise you use the group filtering feature (if possible) to avoid running into group overages.
- You can use the
BulkCreateGroups.ps1provided in the App Creation Scripts folder to create a large number of groups and assign users to them. This will help test overage scenarios during development.⚠️ Remember to change the user's objectId provided in theBulkCreateGroups.ps1script. - When you run this sample and an overage occurred, then you'd see the
_claim_namesin the home page after the user signs-in. - We strongly advise you use the group filtering feature (if possible) to avoid running into group overages.
- In case you cannot avoid running into group overage, we suggest you use the following logic to process groups claim in your token.
- Check for the claim
_claim_nameswith one of the values beinggroups. This indicates overage. - If found, make a call to the endpoint specified in
_claim_sourcesto fetch user’s groups. - If none found, look into the
groupsclaim for user’s groups.
- Check for the claim
When attending to overage scenarios, which requires a call to Microsoft Graph to read the signed-in user's group memberships, your app will need to have the GroupMember.Read.All for the getMemberObjects function to execute successfully.
Developers who wish to gain good familiarity of programming for Microsoft Graph are advised to go through the An introduction to Microsoft Graph for developers recorded session.
Consider the group-guard.service.ts. Here, we are checking whether the token for the user has the _claim_names claim, which indicates that the user has too many group memberships. If so, we redirect the user to the /overage page. There, we initiate a call to MS Graph API's https://graph.microsoft.com/v1.0/me/memberOf endpoint to query the full list of groups that the user belongs to. Finally we check for the designated groupID among this list.
@Injectable({
providedIn: 'root'
})
export class GroupGuardService implements CanActivate {
constructor(private authService: MsalService, private graphService: GraphService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot): boolean {
const expectedGroup = route.data.expectedGroup;
let account: Account = this.authService.instance.getAllAccounts()[0];
this.graphService.user.displayName = account.idTokenClaims?.preferred_username!;
if (this.graphService.user.groupIDs.includes(expectedGroup)) {
return true;
}
if (account.idTokenClaims?.groups) {
this.graphService.user.groupIDs = account.idTokenClaims?.groups;
} else {
if (account.idTokenClaims?._claim_names) {
window.alert('You have too many group memberships. The application will now query Microsoft Graph to get the full list of groups that you are a member of.');
this.router.navigate(['/overage']);
return false;
}
window.alert('Token does not have groups claim');
return false;
}
window.alert('You do not have access for this');
return false;
}
}In app-routing.module.ts, we add GroupGuardService to routes we want to check for group membership:
const routes: Routes = [
{
path: 'todo-edit/:id',
component: TodoEditComponent,
canActivate: [
MsalGuard,
GroupGuardService
],
data: {
expectedGroup: auth.groups.groupMember
}
},
{
path: 'todo-view',
component: TodoViewComponent,
canActivate: [
MsalGuard,
GroupGuardService
],
data: {
expectedGroup: auth.groups.groupMember
}
},
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [
MsalGuard,
GroupGuardService,
],
data: {
expectedGroup: auth.groups.groupAdmin
}
},
];-
In
Startup.cs,OnTokenValidatedevent calls GetSignedInUsersGroups method defined in GraphHelper.cs to process groups overage claim.services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(options => { Configuration.Bind("AzureAd", options); options.Events = new JwtBearerEvents(); options.Events.OnTokenValidated = async context => { if (context != null) { //Calls method to process groups overage claim. await GraphHelper.GetSignedInUsersGroups(context); } }; }, options => { Configuration.Bind("AzureAd", options); }) .EnableTokenAcquisitionToCallDownstreamApi(options => Configuration.Bind("AzureAd", options)) .AddMicrosoftGraph(Configuration.GetSection("GraphBeta")) .AddInMemoryTokenCaches();
AddMicrosoftGraph registers the service for GraphServiceClient. The values for BaseUrl and Scopes defined in GraphAPI section of the appsettings.json.
-
In
GraphHelper.cs, GetSignedInUsersGroups method checks if incoming token contains Group Overage claim then it will call ProcessUserGroupsForOverage method to retrieve groups.public static async Task GetSignedInUsersGroups(TokenValidatedContext context) { // Checks if the incoming token contained a 'Group Overage' claim. if (HasOverageOccurred(context.Principal)) { await ProcessUserGroupsForOverage(context); } }
The ASP.NET middleware supports roles populated from claims by specifying the claim in the RoleClaimType property of TokenValidationParameters.
Since the groups claim contains the object IDs of the security groups than the actual names by default, you'd use the group IDs instead of group names. See Role-based authorization in ASP.NET Core for more info.
// Startup.cs
// The following lines code instruct the asp.net core middleware to use the data in the "groups" claim in the [Authorize] attribute and for User.IsInrole()
// See https://docs.microsoft.com/aspnet/core/security/authorization/roles
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
// Use the groups claim for populating roles
options.TokenValidationParameters.RoleClaimType = "groups";
});
// Adding asp.net core authorization policies that enforce authorization using Azure AD roles.
services.AddAuthorization(options =>
{
options.AddPolicy(AuthorizationPolicies.AssignmentToGroupAdminGroupRequired, policy => policy.RequireRole(Configuration["Groups:GroupAdmin"]));
options.AddPolicy(AuthorizationPolicies.AssignmentToGroupMemberGroupRequired, policy => policy.RequireRole(Configuration["Groups:GroupMember"]));
});
// In code..(Controllers & elsewhere)
[Authorize(Roles = "Group-object-id")] // In controllers
// or
User.IsInRole("Group-object-id"); // In methodsℹ️ Did the sample not work for you as expected? Did you encounter issues trying this sample? Then please reach out to us using the GitHub Issues page.
To debug the .NET Core web API that comes with this sample, install the C# extension for Visual Studio Code.
Learn more about using .NET Core with Visual Studio Code.
- Microsoft identity platform (Azure Active Directory for developers)
- Overview of Microsoft Authentication Library (MSAL)
- Quickstart: Register an application with the Microsoft identity platform
- Quickstart: Configure a client application to access web APIs
- Understanding Azure AD application consent experiences
- Understand user and admin consent
- Initialize client applications using MSAL.js
- Single sign-on with MSAL.js
- Handle MSAL.js exceptions and errors
- Logging in MSAL.js applications
- Pass custom state in authentication requests using MSAL.js
- Prompt behavior in MSAL.js interactive requests
- Use MSAL.js to work with Azure AD B2C
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [azure-active-directory dotnet ms-identity adal msal].
If you find a bug in the sample, raise the issue on GitHub Issues.
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.




