在www.example.com mvc中授权Azure AD组asp.net

zd287kbt  于 2023-01-22  发布在  .NET
关注(0)|答案(1)|浏览(202)

我尝试通过[Authorize(Policy =“nameOfPolicy”)]对控制器中的特定页面视图使用授权,但我一直收到“拒绝访问”,即使我有权访问我在策略中输入的Azure AD组。
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();
        });
    }
}

在我的控制器中,这就是我如何尝试使用授权:

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

gjmwrych1#

在www.example.com MVC中授权Azure AD组asp.net。
我已按照以下步骤操作,并能够授权。
1.在Azure AD中创建应用程序并注册该应用程序。

1.在应用程序的身份验证中使用ID令牌。

1.从身份验证选项卡中为应用程序设置Azure中的RedirectionUrl。

从VisualStudio模板中选择ASP.NetMVC应用程序并安装以下NuGet包。
NuGets

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

在Startup.cs类中,进行以下更改以注册或配置身份验证服务

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

您需要在startup.cs类中添加app.UseAuthentication ()方法沿着app.UseAuthorization()

并且您需要使用Settings.Json文件中的TenantId、ClientId和RedirectionUrl。

应用程序设置.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": "*"
}

启动设置.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] 
public class HomeController : Controller

相关问题