问题
Hi I am trying to implement Azure Groups based authorization in my .net core app. I have more groups like 100 to 200. I have added policies to add authorization.
services.AddAuthorization(options =>
{
options.AddPolicy("GroupsCheck", policy =>
{
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
policy.Requirements.Add(new GroupsCheckRequirement("11b250bf-76c0-4efe-99f2-2d781bae43bb")); //currently hard coded but want to include all the groups returned from MS graph
});
});
Then
GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient();
var groupList = await client.Users[userId].TransitiveMemberOf.Request().GetAsync();
This will return more than 100 groups. Now in policy I want to include all these groups. Is hard coding in config file all the groups will better way? Also my JWT token has only hasgroups:true rather than group ids. So how can I authorize based on groups? can someone help me to find good way? thanks
回答1:
According to my test, if you just want to use groups based authorization, please refer to the following code:
- change Startup.cs
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);
- Add the following code in the controller or method
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
来源:https://stackoverflow.com/questions/60050599/how-to-do-authorization-based-on-azure-ad-groups