An Angular single-page application (SPA) calling a protected Core web API and using Security Groups to implement Role-Based Access Control (RBAC)
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- More information
- Community Help and Support
- Contributing
In Chapter 1 we learnt how to use App Roles for role-based access control. In this chapter, we learn about how to do the same with Azure AD Security Groups.
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.
Authorization in Azure AD can also be done with App Roles, as shown in chapter1. 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.
- The scenario is similar to Chapter 1, except we'd use Security Groups instead of App Roles
File/folder | Description |
---|---|
AppCreationScripts/ |
Contains Powershell scripts to automate app registrations. |
TodoListAPI/ |
Source code of the TodoList API. |
TodoListSPA/ |
Source code of the TodoList client SPA. |
CHANGELOG.md |
List of changes to the sample. |
CONTRIBUTING.md |
Guidelines for contributing to the sample. |
LICENSE |
The license for the sample. |
- Two security groups GroupAdmin and GroupMember, with users you want to test with assigned to them.
Using a command line interface such as VS Code integrated terminal, follow the steps below:
cd chapter2
cd TodoListAPI
dotnet restore
dotnet dev-certs https --clean
dotnet dev-certs https --trust
Learn more about HTTPS in .NET Core.
cd ../
cd TodoListSPA
npm install
There 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
TodoListAPI
. - 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.
- 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
Set
next 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 TodoListAPI
. - For Admin consent description type
Allows the app to access TodoListAPI as the signed-in user.
- For User consent display name type
Access TodoListAPI
. - For User consent description type
Allow the application to access TodoListAPI 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:
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
TodoListAPI\appsettings.json
file. - Find the app key
Domain
and replace the existing value with your Azure AD tenant name. - Find the app key
ClientId
and replace the existing value with the application ID (clientId) of theTodoListAPI
application copied from the Azure portal. - Find the app key
TenantId
and replace the existing value with your Azure AD tenant ID. - Find the app key
ClientSecret
and replace the existing value with the key you saved during the creation of theTodoListAPI
app, 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
TodoListSPA
. - 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.
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
TodoListSPA\src\app\app-config.json
file. - Find the app key
clientId
and replace the existing value with the application ID (clientId) of the TodoListSPA application copied from the Azure portal. - Find the app key
todoListApi.resourceUri
and replace the existing value with the base address of the TodoListAPI project (by defaulthttps://localhost:44351/api/todolist
). - Find the app key
todoListApi.resourceScopes
and replace the existing value with Scope you created earlierapi://{clientId-of-service}/access_as_user
.
For a middle tier web API (TodoListAPI
) to be able to call a downstream web API, the middle tier app needs to be granted the required permissions as well. However, since the middle tier cannot interact with the signed-in user, it needs to be explicitly bound to the client app in its Azure AD registration. This binding merges the permissions required by both the client and the middle tier web API and presents it to the end user in a single consent dialog. The user then consent to this combined set of permissions.
To achieve this, you need to add the Application Id of the client app, in the Manifest of the web API in the knownClientApplications
property. Here's how:
-
In the Azure portal, navigate to your
TodoListAPI
app registration, and select Manifest section. -
In the manifest editor, change the
"knownClientApplications": []
line so that the array contains the Client ID of the client application (TodoListSPA
) as an element of the array.For instance:
"knownClientApplications": ["ca8dca8d-f828-4f08-82f5-325e1a1c6428"],
-
Save the changes to the manifest.
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
samAccountName
orOn Premises Group Security Identifier
instead 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 groups
or theAll groups (includes distribution lists but not groups assigned to the application)
option. Choosing both negates the effect ofSecurity Groups
option. - 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 Groups
orAll 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 thegroups
claim 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 ID
option under the Access section. This will result in Azure AD sending the Object ID of the groups the user is assigned to in thegroups
claim 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
groups
claim 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
TodoListSPA\src\app\app-config.json
file. - Find the app key
groups.groupAdmin
and replace the existing value with the object ID of the GroupAdmin group copied from the Azure portal. - Find the app key
groups.groupMember
and 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
TodoListAPI\appsettings.json
file. - Find the app key
Groups.GroupAdmin
and replace the existing value with the object ID of the GroupAdmin group copied from the Azure portal. - Find the app key
Groups.GroupMember
and 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 TodoListSPA
npm start
In a separate console window, execute the following commands:
cd TodoListAPI
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.ps1
provided 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.ps1
script. - When you run this sample and an overage occurred, then you'd see the
_claim_names
in 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_names
with one of the values beinggroups
. This indicates overage. - If found, make a call to the endpoint specified in
_claim_sources
to fetch user’s groups. - If none found, look into the
groups
claim 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
,OnTokenValidated
event 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.
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
azure-ad-b2c
ms-identity
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 [email protected] with any additional questions or comments.