我正在尝试构建一个小型Web应用程序,该应用程序将使用Azure AD对访问用户进行身份验证,然后将用户添加到Azure AD中的指定组。使用的组件是C#/ dotnet核心,MSAL和.NET的Microsoft Graph库。
步骤很简单:
该应用程序在Azure AD中注册,具有隐式授权(对于ID令牌)并具有以下Azure AD权限:
控制器看起来像这样:
public async Task<string> Test()
{
//get authenticated user
var identity = User.Identity as ClaimsIdentity;
string preferred_username = identity.Claims.FirstOrDefault(c => c.Type == "preferred_username")?.Value;
//get appsettings.json
var azureAdOptions = new AzureADOptions();
_configuration.Bind("AzureAd", azureAdOptions);
//do Microsoft Graph stuff
GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
async requestMessage =>
{
string authority = $"{azureAdOptions.Instance}{azureAdOptions.TenantId}";
ClientCredential clientCredentials = new ClientCredential(azureAdOptions.ClientSecret);
var app = new ConfidentialClientApplication(azureAdOptions.ClientId, authority, "https://daemon",
clientCredentials, null, new TokenCache());
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
// Passing tenant ID to the sample auth provider to use as a cache key
AuthenticationResult authResult = null;
authResult = await app.AcquireTokenForClientAsync(scopes);
// Append the access token to the request
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}));
User userToAdd = await graphClient.Users[preferred_username].Request().GetAsync();
await graphClient.Groups["c388b7a4-2a22-4e3f-ac11-900cef9f74c6"].Members.References.Request().AddAsync(userToAdd);
return $"added {userToAdd.DisplayName} to group";
}
Startup.cs看起来像这样:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.Authority = options.Authority + "/v2.0/";
options.TokenValidationParameters.ValidateIssuer = true;
});
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
使用此代码,我有两个身份验证流程。一个用于验证访问用户,另一个用于向Microsoft Graph验证应用程序。这背后的基本原理是用户没有足够的权限将成员添加到组中。代码工作并完全按预期执行。
针对单个Azure AD应用程序注册的双重身份验证流是确保此目标的最佳方式,还是需要一个只需要一个身份验证流的时尚设计?
据我所知,你确实需要支持这两个流程。您的用户需要一个令牌与您的Web应用程序通信,您的Web应用程序需要一个不同的令牌才能与Graph交谈。
希望您很快就不需要DelegateAuthenticationProvider中的所有代码,因为我们很快就会预览一堆基于场景的AuthenticationProviders。 ClientCredentialProvider应该为你工作。