page_type | name | description | languages | products | urlFragment | extensions | |||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
Add authorization using app roles & roles claims to an ASP.NET Core web app that signs-in users with the Microsoft identity platform |
|
|
active-directory-aspnetcore-webapp-openidconnect-v2 |
|
Add authorization using app roles & roles claims to an ASP.NET Core web app that signs-in users with the Microsoft identity platform
- Overview
- Scenario
- Overview
- Scenario
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- How the code was created
- How to deploy this sample to Azure
- Next Steps
- Contributing
- Learn More
This sample demonstrates a ASP.NET Core Web App calling Microsoft Graph.
ℹ️ To learn how applications integrate with Microsoft Graph, consider going through the recorded session:: An introduction to Microsoft Graph for developers
In doing so, it introduces Role-based Access Control (RBAC) by using Microsoft Entra ID's App Roles.
Role based access control in Microsoft Entra ID can be done with Delegated and App permissions and Security Groups as well. We will cover RBAC using Security Groups in the next tutorial. Delegated and App permissions, Security Groups and App Roles in Microsoft Entra ID are by no means mutually exclusive - they can be used in tandem to provide even finer grained access control.
ℹ️ To learn more on using security groups and app roles in your app AD,consider going through the recorded session: Implement authorization in your applications with App roles and Security Groups with the Microsoft identity platform
This sample shows how a .NET Core MVC Web app that uses OpenID Connect to sign in users and use Microsoft Entra ID App Roles for authorization. App Roles, along with Security groups are popular means to implement authorization.
This application implements RBAC using Microsoft Entra ID's App roles & Role Claims feature. Another approach is to use Microsoft Entra groups and Group Claims, as shown in WebApp-GroupClaims. Microsoft Entra groups and App Roles are by no means mutually exclusive; they can be used in tandem to provide even finer grained access control.
Using RBAC with App roles and Role Claims, developers can securely enforce authorization policies with minimal effort on their part.
- A Microsoft Identity Platform Office Hours session covered Microsoft Entra app roles and security groups, featuring this scenario and this sample. A recording of the session is is provided in this video Using Security Groups and App roles in your apps
For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Microsoft Entra ID.
This sample first leverages the ASP.NET Core OpenID Connect middleware to sign in the user. On the home page it displays the various claims
that the user's ID Token contained. The ID token is used by the asp.net security middleware to build the ClaimsPrincipal, accessible via HttpContext.User in the code.
This web application allows users to list all users in their tenant or a list of all the app roles and groups the signed in user is assigned to. The idea is to provide an example of how, within an application, access to certain functionality is restricted to subsets of users based on which role they belong to. The sample also shows how to use the app roles in Policy-based authorization in ASP.NET Core.
This type of authorization is implemented using role-based access control (RBAC). When using RBAC, an administrator grants permissions to roles, not to individual users or groups. The administrator can then assign roles to different users and groups to control who has then access to certain content and functionality within the application.
This sample application defines the following two App roles:
DirectoryViewers
: Have the ability to view any directory user's roles and security group assignments.UserReaders
: Have the ability to view a list of users in the directory.
These App roles are defined in the Microsoft Entra admin center in the application's registration manifest. When a user signs into the application, Microsoft Entra ID emits a roles
claim for each role that the user has been granted individually to the user in the from of role membership. Assignment of users and groups to roles can be done through the portal's UI, or programmatically using the Microsoft Graph and Azure AD Powershell. In this sample, application role management is done through the Microsoft Entra admin center or using PowerShell.
NOTE: Role claims will not be present for guest users in a tenant if the https://login.microsoftonline.com/common/
endpoint is used as the authority to sign in users. Microsoft Entra ID can emit app roles only if the tenanted end point https://login.microsoftonline.com/{tenant Id}/
is being used.
- Either Visual Studio or Visual Studio Code and .NET Core SDK
- An Microsoft Entra ID tenant. For more information, see: How to get a Microsoft Entra tenant
- A user account in your Microsoft Entra ID tenant.
This sample will not work with a personal Microsoft account. If you're signed in to the Microsoft Entra admin center with a personal Microsoft account and have not created a user account in your directory before, you will need to create one before proceeding.
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2.git
or 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 5-WebApp-AuthZ\5-1-Roles
There is one project in this sample. To register it, you can:
- follow the steps below for manually register your apps
- or use PowerShell scripts that:
- automatically creates the Microsoft Entra applications and related objects (passwords, permissions, dependencies) for you.
- modify the projects' configuration files.
Expand this section if you want to use this automation:
> :warning: If you have never used **Microsoft Graph PowerShell** before, we recommend you go through the [App Creation Scripts Guide](./AppCreationScripts/AppCreationScripts.md) once to ensure that your environment is prepared correctly for this step.
1. On Windows, run PowerShell as **Administrator** and navigate to the root of the cloned directory
1. In PowerShell run:
```PowerShell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
```
1. Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly.
1. For interactive process -in PowerShell, run:
```PowerShell
cd .\AppCreationScripts\
.\Configure.ps1 -TenantId "[Optional] - your tenant id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'"
```
> Other ways of running the scripts are described in [App Creation Scripts guide](./AppCreationScripts/AppCreationScripts.md). The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
To manually register the apps, as a first step you'll need to:
- Sign in to the Microsoft Entra admin center.
- If your account is present in more than one Microsoft Entra tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory to change your portal session to the desired Microsoft Entra tenant.
- Navigate to the Microsoft Entra admin center and select the Microsoft Entra ID 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
WebApp-RolesClaims
. - Under Supported account types, select Accounts in this organizational directory only
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- In the app's registration screen, select the Authentication blade to the left.
- If you don't have a platform added, select Add a platform and select the Web option.
- In the Redirect URI section enter the following redirect URIs:
https://localhost:44321/
https://localhost:44321/signin-oidc
- In the Front-channel logout URL section, set it to
https://localhost:44321/signout-oidc
. - Click Save to save your changes.
- In the Redirect URI section enter the following redirect URIs:
- In the app's registration screen, select the Certificates & secrets blade in the left to open the page where you 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 (6 months, 12 months or Custom) as per your security posture.
- The generated key value will be displayed when you select the Add button. Copy and save the generated value for use in later steps.
- 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 Microsoft Entra admin center before navigating to any other screen or blade.
💡 For enhanced security, instead of using client secrets, consider using certificates and Azure KeyVault.
- Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
- 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
- Since this app signs-in users, we will now proceed to select delegated permissions, which is requested by apps that signs-in users.
- In the Delegated permissions section, select User.Read, User.ReadBasic.All in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Type a key description (for instance
-
Still on the same app registration, select the App roles blade to the left.
-
Select Create app role:
- For Display name, enter a suitable name, for instance UserReaders.
- For Allowed member types, choose User.
- For Value, enter UserReaders.
- For Description, enter User readers can read basic profiles of all users in the directory..
Repeat the steps above for another role named DirectoryViewers
- Select Apply to save your changes.
To add users to this app role, follow the guidelines here: Assign users and groups to roles.
💡 Important security tip
When you set User assignment required? to Yes, Microsoft Entra ID will check that only users assigned to your application in the Users and groups blade are able to sign-in to your app.To enable this, follow the instructions here. You can assign users directly or by assigning security groups they belong to.
For more information, see: How to: Add app roles in your application and receive them in the token
- Still on the same app registration, select the Token configuration blade to the left.
- Select Add optional claim:
- Select optional claim type, then choose ID.
- Select the optional claim acct.
Provides user's account status in tenant. If the user is a member of the tenant, the value is 0. If they're a guest, the value is 1.
- Select Add to save your changes.
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
appsettings.json
file. - Find the key
ClientId
and replace the existing value with the application ID (clientId) ofWebApp-RolesClaims
app copied from the Microsoft Entra admin center. - Find the key
TenantId
and replace the existing value with your Microsoft Entra tenant/directory ID. - Find the key
Domain
and replace the existing value with your Microsoft Entra tenant domain, ex.contoso.onmicrosoft.com
. - Find the key
ClientSecret
and replace the existing value with the generated secret that you saved during the creation ofWebApp-RolesClaims
copied from the Microsoft Entra admin center.
Follow README-use-certificate.md to know how to use this option.
From your shell or command line, execute the following commands:
cd 5-WebApp-AuthZ\5-1-Roles
dotnet run
Expand the section
- Open your web browser and make a request to the app. The app immediately attempts to authenticate you via the Microsoft identity platform endpoint. Sign in using an user account in that tenant.
- On the home page, the app lists the various claims it obtained from your ID token. You'd notice a claim named
roles
. There will be oneroles
claim for each app role the signed-in use is assigned to. - There also are two links provided on the home page under the Try one of the following Azure App Role driven operations heading. These links will result in an access denied error if the signed-in user is not present in the expected role. Sign-out and sign-in with a user account with the correct role assignment to view the contents of these pages. When you click on the page that fetches the signed-in user's roles and group assignments, the sample will attempt to obtain consent from you for the User.Read permission using incremental consent.
- When a user was not added to any of the required groups (UserReader and/or DirectoryViewers), clicking on the links will result in
Access Denied
message on the page. Also looking intoClaims from signed-in user's token
don't have roles claim. - Add an user to at lease one of the groups. You will be able to get corresponding information when clicking links on main page. Also you can see a roles claim printed as part of claims on main page.
You can use
AppCreationScripts/CreateUsersAndAssignRoles.ps1
andAppCreationScripts/CleanupUsersAndAssignRoles.ps1
to create and remove 2 users correspondingly. The scripts also will assign roles required by the sample.
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.
Expand for troubleshooting info
ASP.NET core applications create session cookies that represent the identity of the caller. Some Safari users using iOS 12 had issues which are described in ASP.NET Core #4467 and the Web kit bugs database Bug 188165 - iOS 12 Safari breaks ASP.NET Core 2.1 OIDC authentication.
If your web site needs to be accessed from users using iOS 12, you probably want to disable the SameSite protection, but also ensure that state changes are protected with CSRF anti-forgery mechanism. See the how to fix section of Microsoft Security Advisory: iOS12 breaks social, WSFed and OIDC logins #4647
To provide feedback on or suggest features for Microsoft Entra ID, visit User Voice page.
Expand the section
The ASP.NET middleware supports roles populated from claims by specifying the claim in the RoleClaimType
property of TokenValidationParameters
.
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// [removed for brevity]
// This is required to be instantiated before the OpenIdConnectOptions starts getting configured.
// By default, the claims mapping will map claim names in the old format to accommodate older SAML applications.
// 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles'
// This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
// The following lines code instruct the asp.net core middleware to use the data in the "groups" claim in the Authorize attribute and User.IsInrole()
// See https://docs.microsoft.com/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 for more info.
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
// Use the groups claim for populating roles
options.TokenValidationParameters.RoleClaimType = "roles";
});
// Adding authorization policies that enforce authorization using Microsoft Entra roles.
services.AddAuthorization(options =>
{
options.AddPolicy(AuthorizationPolicies.AssignmentToUserReaderRoleRequired, policy => policy.RequireRole(AppRole.UserReaders));
options.AddPolicy(AuthorizationPolicies.AssignmentToDirectoryViewerRoleRequired, policy => policy.RequireRole(AppRole.DirectoryViewers));
});
// [removed for brevity]
}
// In code..(Controllers & elsewhere)
[Authorize(Policy = AuthorizationPolicies.AssignmentToDirectoryViewerRoleRequired)]
// or
User.IsInRole("UserReaders"); // In methods
The class GraphHelper.cs is where the logic to initialize the MS Graph SDK along with logic to enable this app for Continuous Access Evaluation
Expand the section
-
Open the generated project (.csproj) in Visual Studio, and save the solution.
-
Add the
Microsoft.Identity.Web.csproj
project which is located at the root of this sample repo, to your solution (Add Existing Project ...). It's used to simplify signing-in and, in the next tutorial phases, to get a token -
Add a reference from your newly generated project to
Microsoft.Identity.Web
(right click on the Dependencies node under your new project, and choose Add Reference ..., and then in the projects tab find theMicrosoft.Identity.Web
project) -
Open the Startup.cs file and:
-
in the
ConfigureServices
method, the following lines:services.AddAuthentication(AzureADDefaults.AuthenticationScheme) .AddAzureAD(options => Configuration.Bind("AzureAd", options));
have been replaced by these lines:
//This enables your application to use the Microsoft identity platform endpoint. This endpoint is capable of signing-in users both with their Work and School and Microsoft Personal accounts. services.AddMicrosoftIdentityWebAppAuthentication(Configuration) .EnableTokenAcquisitionToCallDownstreamApi(new string[] { Constants.ScopeUserRead }) .AddInMemoryTokenCaches(); // Adds aspnetcore MemoryCache as Token cache provider for MSAL. services.AddGraphService(Configuration); // Adds the IMSGraphService as an available service for this app.
-
-
In the
ConfigureServices
method of `Startup.cs', add the following lines:// This is required to be instantiated before the OpenIdConnectOptions starts getting configured. // By default, the claims mapping will map claim names in the old format to accommodate older SAML applications. // 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles' // This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token JwtSecurityTokenHandler.DefaultMapInboundClaims = false; // Adding authorization policies that enforce authorization using Microsoft Entra roles. services.AddAuthorization(options => { options.AddPolicy(AuthorizationPolicies.AssignmentToUserReaderRoleRequired, policy => policy.RequireRole(AppRole.UserReaders)); options.AddPolicy(AuthorizationPolicies.AssignmentToDirectoryViewerRoleRequired, policy => policy.RequireRole(AppRole.DirectoryViewers)); });
-
In the
ConfigureServices
method of `Startup.cs', the following lines instruct the ASP.NET security middleware to use the roles claim to fetch roles for authorization.// Add this configuration after the call to `AddMicrosoftWebAppAuthentication`. services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options => { // The claim in the JWT token where App roles are available. options.TokenValidationParameters.RoleClaimType = "roles"; });
-
In the
HomeController.cs
, the following method is added with theAuthorize
attribute with the name of the policy that enforces that the signed-in user is present in the app role UserReaders, that permits listing of users in the tenant.[Authorize(Policy = AuthorizationPolicies.AssignmentToUserReaderRoleRequired)] public async Task<IActionResult> Users() {
-
A new class called
AccountController.cs
is introduced. This contains the code to intercept the default AccessDenied error's route and present the user with an option to sign-out and sign-back in with a different account that has access to the required role.[AllowAnonymous] public IActionResult AccessDenied() {
-
The following method is also added with the
Authorize
attribute with the name of the policy that enforces that the signed-in user is present in the app role DirectoryViewers, that permits listing of roles and groups the signed-in user is assigned to.[Authorize(Policy = AuthorizationPolicies.AssignmentToDirectoryViewerRoleRequired)] public async Task<IActionResult> Groups() {
-
The views,
Users.cshtml
andGroups.cshtml
have the code to display the users in a tenant and roles and groups the signed-in user is assigned to respectively.
Expand the section
This project has one WebApp project. To deploy it to Azure Web Sites, you'll need, :
- create an Azure Web Site
- publish the Web App to the web site, and
- update its client(s) to call the web site instead of IIS Express.
- Sign in to the Microsoft Entra admin center.
- Click
Create a resource
in the top left-hand corner, select Web --> Web App, and give your web site a name, for example,WebApp-RolesClaims-contoso.azurewebsites.net
. - Thereafter select the
Subscription
,Resource Group
,App service plan and Location
.OS
will be Windows andPublish
will be Code. - Click
Create
and wait for the App Service to be created. - Once you get the
Deployment succeeded
notification, then click onGo to resource
to navigate to the newly created App service. - Once the web site is created, locate it in the Dashboard and click it to open App Services Overview screen.
- From the Overview tab of the App Service, download the publish profile by clicking the Get publish profile link and save it. Other deployment mechanisms, such as from source control, can also be used.
- Switch to Visual Studio and go to the WebApp-RolesClaims project. Right click on the project in the Solution Explorer and select Publish. Click Import Profile on the bottom bar, and import the publish profile that you downloaded earlier.
- Click on Configure and in the
Connection tab
, update the Destination URL so that it is ahttps
in the home page url, for example https://WebApp-RolesClaims-contoso.azurewebsites.net. Click Next. - On the Settings tab, make sure
Enable Organizational Authentication
is NOT selected. Click Save. Click on Publish on the main screen. - Visual Studio will publish the project and automatically open a browser to the URL of the project. If you see the default web page of the project, the publication was successful.
- Navigate back to to the Microsoft Entra admin center. In the left-hand navigation pane, select the Microsoft Entra ID service, and then select App registrations (Preview).
- In the resultant screen, select the
WebApp-RolesClaims
application. - In the Authentication | page for your application, update the Logout URL fields with the address of your service, for example https://WebApp-RolesClaims-contoso.azurewebsites.net
- From the Branding menu, update the Home page URL, to the address of your service, for example https://WebApp-RolesClaims-contoso.azurewebsites.net. Save the configuration.
- Add the same URL in the list of values of the Authentication -> Redirect URIs menu. If you have multiple redirect urls, make sure that there a new entry using the App service's Uri for each redirect url.
Learn how to:
- Change your app to sign-in users from any organization or Microsoft accounts
- Enable users from National clouds to sign-in to your application
- Enable your web app to call a web API on behalf of the signed-in user
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.