Vinny
Vinny

Reputation: 619

Get Token from Azure using AAD App (ClientID, TenantID, Cert-Thumbprint)

I have below Method to get a token from Azure using ClientID, TenantID and AADAppPassword

This is working awesome but now I need to switch to different AAD AppID and use Certificate Thumbprint Or Certificate pfx. I don't want to change my 1000+ lines of code.

Can someone help me get a token the same way I'm getting using below Method but use Certificate Thumbprint instead and which returns token so that I can call the method right before I'm about to make rest API call.

public static async Task<string> GetAccessToken(string tenantId, string clientId, string clientKey)
        {
            string authContextURL = "https://login.windows.net/" + tenantId;
            var authenticationContext = new AuthenticationContext(authContextURL);
            var credential = new ClientCredential(clientId, clientKey);
            var result = await authenticationContext

            .AcquireTokenAsync("https://management.azure.com/", credential);
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }
            string token = result.AccessToken;
            return token;
    }

Upvotes: 1

Views: 2943

Answers (1)

You must use ClientAssertionCertificate instead of ClientCredential

X509Certificate2 cert = ReadCertificateFromStore(config.CertName);
certCred = new ClientAssertionCertificate(config.ClientId, cert);
result = await authContext.AcquireTokenAsync(todoListResourceId, certCred);

You may refer the Azure AD v1 Sample for this.

MSAL.NET is now the recommended auth library to use with the Microsoft identity platform. No new features will be implemented on ADAL.NET. The efforts are focused on improving MSAL. You can refer the documentation here if you are planning to migrate applications to MSAL.NET

Upvotes: 1

Related Questions