Search code examples
asp.net-coreazure-authenticationmicrosoft-entra-id

How to allow users from specific Microsoft Entra ID tenants to access an ASP.NET Core web app


I am developing an ASP.NET Core web application that is used to exchange data between me and a third party. The app is using the Microsoft Identity Platform to authenticate users. I want to create app registration for two tenants only, so that admins of both tenants can independently create and delete web app users. Users from other tenants should not be allowed to access the app.

Here is what I have done so far:

  1. Created an ASP.NET Core web app.
  2. Integrated Microsoft Identity Platform for authentication.
  3. Registered the app in Microsoft Entra ID for my tenant.

My questions are:

  1. How do I register the app for two specific tenants?
  2. How can I configure the app to restrict access to only these two tenants?
  3. What settings or configurations are needed to allow admins of these tenants to manage users independently?

This is what the AzureAd configuration looks like in the appsettings.json file:

{
  "AzureAd": {
    "Instance": "[my instance]",
    "Domain": "[my domain]",
    "ClientId": "[my client id]",
    "TenantId": "organizations",
    "CallbackPath": "/signin-oidc"
  },
}

This is the relevant code snippet from Startup.cs:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
           services.AddRazorPages()
                .AddMicrosoftIdentityUI();

Solution

  • I agree with @Jason Pan, to allow only two tenants to access the application, make use of below code snippet.

    • You can extend the token validation and make sure it is restricted to Microsoft Entra tenants registered in the application configuration.
    • Initially get the list of tenants allowed from configuration and configure OnTokenValidated event to filter the tenants.
    • If the TenantID does not match then it will throw an Unauthorized Access Exception.

    For sample:

    {
      "AllowedTenants": ["tenant1", "tenant2"]
    }
    
    //get list of allowed tenants from configuration
      var allowedTenants = Configuration.GetSection("AzureAd:AllowedTenants").Get<string[]>();
      services.Configure<JwtBearerOptions>(
          JwtBearerDefaults.AuthenticationScheme, options =>
          {
              var existingOnTokenValidatedHandler = options.Events.OnTokenValidated;
              options.Events.OnTokenValidated = async context =>
              {
                  await existingOnTokenValidatedHandler(context);
                  if (!allowedTenants.Contains(context.Principal.GetTenantId()))
                  {
                      throw new UnauthorizedAccessException("This tenant is not authorized");
                  }
              };
          });
    

    You can use the tenant ID tid value in the access token to permit or restrict access for specific tenants based on your requirement.

    enter image description here

    To manage users, you can grant User.ReadWrite.All API permission to the Microsoft Entra ID application:

    enter image description here

    And pass scope as Microsoft Graph:

      "DownstreamApis": {
        "MicrosoftGraph": {
          // Specify BaseUrl if you want to use Microsoft graph in a national cloud.
       // "BaseUrl": "https://graph.microsoft.com/v1.0",
          "Scopes": [ "User.Read","User.ReadWrite.All" ]
    

    And call the Microsoft Graph APIs. Refer this GitHub blog and SO Thread by Md Farid Uddin Kiron for more detail.

    References:

    active-directory-aspnetcore-webapp-openidconnect-v2/2-WebApp-graph-user/2-3-Multi-Tenant/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2 · GitHub

    Restricting multi tenant application in Azure AD - Microsoft Q&A by Vasil Michev