Can someone show me how to get group names that currently signed in user belong to in ASP.NET Core 7 ?
Note that I'm using a certificate and not client secret to access Azure AD. Most of the examples I've come across are using client secret but none show how to do this using a certificate.
I created an Self-Signed certificate using PowerShell:
$certname = "testruk"
$cert = New-SelfSignedCertificate -Subject "CN=$certname" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256
Export-Certificate -Cert $cert -FilePath "C:/test/$certname.cer"
Now, export the above certificate to .pfx
:
$mypwd = ConvertTo-SecureString -String "password" -Force -AsPlainText
Export-PfxCertificate -Cert $cert -FilePath "C:/test/$certname.pfx" -Password $mypwd
I created an Azure AD Application and uploaded the .cer
certificate:
And granted API permissions:
To authenticate to the Azure AD Application using certificate, I used the below code:
using Microsoft.Identity.Client;
using System.Security.Cryptography.X509Certificates;
X509Certificate2 certificate = new X509Certificate2("C:\\Users\\**\\Desktop\\testruk.pfx", "password");
string authority = "https://login.microsoftonline.com/TenantID";
string clientId = "ClientID"; /
string[] scopes = new string[] { "https://graph.microsoft.com/.default"};
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithAuthority(authority)
.WithCertificate(certificate)
.Build();
var authRequestUrl = confidentialClientApplication.GetAuthorizationRequestUrl(scopes);
string authorizationCode = "AuthorizationCodeFromRedirect";
AuthenticationResult authResult = await confidentialClientApplication.AcquireTokenByAuthorizationCode(scopes, authorizationCode).ExecuteAsync();
Console.WriteLine("Access token: {0}", authResult.AccessToken);
The Access token generated successfully:
When I decoded the access token, the scopes are displayed:
By using the above access token, you can call the Microsoft Graph API.
For sample, I used Postman to list the details of signed-in user using the above generated access token:
https://graph.microsoft.com/v1.0/me/memberOf
Reference: