Search code examples
c#asp.net-coreazure-active-directory

How to use certificate with Graph API to get Groups user belongs to


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.


Solution

  • 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"
    

    enter image description here

    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 
    

    enter image description here

    I created an Azure AD Application and uploaded the .cer certificate:

    enter image description here

    And granted API permissions:

    enter image description here

    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:

    enter image description here

    When I decoded the access token, the scopes are displayed:

    enter image description here

    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
    

    enter image description here

    Reference:

    List a user's direct memberships - Microsoft Graph v1.0