更新时间:2023-02-06 22:52:22
根据我的测试,如果您只想使用基于组的授权,请参考以下代码:
According to my test, if you just want to use groups based authorization, please refer to the following code:
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => configuration.Bind(configSectionName, options));
services.Configure<AzureADOptions>(options => configuration.Bind(configSectionName, options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.Authority = options.Authority + "/v2.0/";
options.TokenValidationParameters.NameClaimType = "preferred_username";
// Use the groups claim for populating roles
options.TokenValidationParameters.RoleClaimType = "groups";
});
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.SetCompatibilityVersion(CompatibilityVersion.Latest);
if(User.Identity.IsAuthenticated){
if (User.IsInRole("<group id>"))
{
// do other action
}
else if (User?.FindFirst("_claim_names")?.Value != null)
{
/* call Graph API to check if the user is in the group
for example
GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient();
var memberOfGroups= await client.Me.TransitiveMemberOf.Request().GetAsync();
do
{
bool breakLoops = false;
foreach (var directoryObject in memberOfGroups.CurrentPage)
{
if (directoryObject is Group)
{
Group group = directoryObject as Group;
if (group.Id == "<group id>") {
breakLoops = true;
break;
}
}
}
if (breakLoops)
{
break;
}
if (memberOfGroups.NextPageRequest != null)
{
memberOfGroups = await memberOfGroups.NextPageRequest.GetAsync();
}
else
{
memberOfGroups = null;
}
} while (memberOfGroups != null);
*/
}
else {
// do not have enough permissions
}
}
For more details, please refer to the sample