Search code examples
asp.netasp.net-mvcazure-active-directorymicrosoft-graph-apiazure-ad-graph-api

MS Graph: How to get access token using certificate from Azure


In Asp.Net 4.8 MVC application, I would like to get access token using certificate (self-sgined cert) from Azure AD. All the example I have seen are using client secret. I'm new to Azure AD, so it will be great if someone can point me to a sample that uses certificate.

So far I have googled and examples that I have seen on MS site are using client secret.


Solution

  • I tried to get access token from Console App using client certificate and got below results:

    I created one self-signed certificate from PowerShell using below script:

    $certname = "sricert"    
    $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"   ## Specify your preferred location
    

    Response:

    enter image description here

    To export the above certificate in .pfx format, I ran below commands:

    $mypwd = ConvertTo-SecureString -String "password" -Force -AsPlainText 
    Export-PfxCertificate -Cert $cert -FilePath "C:/test/$certname.pfx" -Password $mypwd 
    

    Response:

    enter image description here

    Now, I registered one Azure AD application and added client certificate with .cer format like this:

    enter image description here

    I ran below c# code including certificate path in my console app and got access token successfully like this:

    using Microsoft.Identity.Client;
    using System.Security.Cryptography.X509Certificates;
    
    // Load the certificate from a file
    X509Certificate2 certificate = new X509Certificate2("C:/test/sricert.pfx", "password");
    
    // Create the confidential client application object
    IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
        .Create("appID")
        .WithCertificate(certificate)
        .WithAuthority(new Uri("https://login.microsoftonline.com/<tenantID>"))
        .Build();
    
    // Get the access token
    string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
    AuthenticationResult authResult = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();
    
    // Print the access token
    Console.WriteLine("Access token: {0}", authResult.AccessToken);
    

    Response:

    enter image description here

    When I decoded the above token in jwt.ms, I got claims like below:

    enter image description here