简体   繁体   中英

Authorize for Azure AD groups in asp.net mvc

I am trying to use authorization on specific page views in controllers with [Authorize(Policy = "nameOfPolicy")] but I keep getting "Access denied" even though I have access to the Azure AD group that I have entered in my policy.

Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        
    }

    public IConfiguration Configuration { get; }
    
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Get the scopes from the configuration (appsettings.json)
        var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
        

        // Add sign-in with Microsoft
        services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))

            // Add the possibility of acquiring a token to call a protected web API
            .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)

            // Enables controllers and pages to get GraphServiceClient by dependency injection
            // And use an in memory token cache
            .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
            .AddDistributedTokenCaches();
        
        services.AddAuthorization(options =>
        {
            options.AddPolicy("it", policy => policy.RequireClaim("groups", "Azure group ID here"));
        });
        
        // Register AadService and PbiEmbedService for dependency injection
        services.AddScoped(typeof(AadService))
                .AddScoped(typeof(PbiEmbedService))
                .AddScoped(typeof(PowerBiServiceApi));

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

        // Enables a UI and controller for sign in and sign out.
        services.AddRazorPages()
            .AddMicrosoftIdentityUI();
        
        // Session/cookie variables etc

        services.AddDistributedMemoryCache();
        services.AddSession();
        
        
        // Loading appsettings.json in C# Model classes
        services.Configure<AzureAd>(Configuration.GetSection("AzureAd"))
                .Configure<PowerBI>(Configuration.GetSection("PowerBI"));
        
        // Add the UI support to handle claims challenges
        services.AddServerSideBlazor()
            .AddMicrosoftIdentityConsentHandler();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseSession();
        
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });
    }
}

And in my controller this is how I try to use the Authorize:

[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
[Authorize(Policy = "it")]
public Task<IActionResult> Index()

To authorize for Azure AD groups in asp.net MVC.

I have followed the below steps and able to authorize.

  1. Create an APP in Azure AD and register the App.

在此处输入图像描述

  1. Using the ID tokens in authentication for the App.

在此处输入图像描述

  1. Set the RedirectionUrl in azure for the App from the authentication tab.

在此处输入图像描述

Choose the ASP.Net MVC application from Visual studio templates and install the below NuGet packages.

NuGets

Microsoft.AspNetCore.Authentication.AzureAD.UI
Microsoft.Identity.Web

In Startup.cs class make the below changes to register or configure the services of Authentication

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApp(Configuartion.GetSetion("AzureAd"));
            services.AddControllersWithViews();
        }

And you need add app.UseAuthentication () method along with app.UseAuthorization() in startup.cs class.

在此处输入图像描述

And you need to use the TenantId, ClientId and RedirectionUrl in the Settings.Json file.

appsettings.json

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "Project",
    "ClientId": "",
    "TenantId": "",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

launchSettings.Json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:42313",
      "sslPort": 44302
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MVC_APP": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:41222",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Authorize attribute need to be add at the controller level.

[Authorize] 
public class HomeController : Controller

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM