Hi Tomar, when we use Azure AD as the authentication scheme in our web application, Microsoft already provide Graph API to query most of the user information. For example, this API help us to query all the groups this user belongs to.According to the api document, we could see that it requires API permissions. So that we additionally need to go to Azure AD -> registered app -> Certificates & Secrets to create a client secret, and in the API permissions blade to add required API permissions.
Then let's use Graph SDK into the web app, refer to my codes below.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
builder.Services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
builder.Services.AddRazorPages()
.AddMicrosoftIdentityUI();
[Authorize]
public class HomeController : Controller
{
private GraphServiceClient _graphServiceClient;
public HomeController(GraphServiceClient graphServiceClient)
{
_graphServiceClient = graphServiceClient;
}
public async Task<IActionResult> IndexAsync()
{
var res = await _graphServiceClient.Me.MemberOf.GetAsync();
List<Group> groups = new List<Group>();
foreach (var obj in res.Value) {
if (obj.OdataType == "#microsoft.graph.group") {
groups.Add((Group)obj);
Group temp = (Group)obj;
var groupName = temp.DisplayName;
}
}
return View();
}
}
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "client_id",
"ClientSecret": "client_secret",
"Domain": "TenantId",
"TenantId": "TenantId",
"CallbackPath": "/signin-oidc"
},
"Graph": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.read"
},
My test result
================================================
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Tiny