[英]Is there a way to authenticate an ASP.NET Core MVC controller action using an Azure AD token?
[英]Authorize for Azure AD groups in asp.net mvc
我正在嘗試使用 [Authorize(Policy = "nameOfPolicy")] 對控制器中的特定頁面視圖使用授權,但即使我可以訪問我在策略中輸入的 Azure AD 組,我仍然收到“訪問被拒絕”。
啟動.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();
});
}
}
在我的 controller 中,這是我嘗試使用授權的方式:
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
[Authorize(Policy = "it")]
public Task<IActionResult> Index()
為 asp.net MVC 中的 Azure AD 組授權。
我已按照以下步驟進行操作並能夠授權。
從 Visual Studio 模板中選擇 ASP.Net MVC 應用程序並安裝以下 NuGet 包。
NuGets
Microsoft.AspNetCore.Authentication.AzureAD.UI
Microsoft.Identity.Web
在 Startup.cs class 中進行以下更改以注冊或配置身份驗證服務
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApp(Configuartion.GetSetion("AzureAd"));
services.AddControllersWithViews();
}
並且您需要在startup.cs
class 中添加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": "*"
}
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"
}
}
}
}
需要在controller級別添加授權屬性。
[Authorize]
public class HomeController : Controller
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.