Search code examples
c#azureazure-active-directoryazure-authentication

Generate access token to authenticate Azure Active directory App


I am using Azure Active Directory App to authenticate my rest endpoint deployed on Azure. I was using pfx cert type and below code to generate access token so that my endpoint can be accessed through that access token.

        var authority = string.Format(authorityUri, credentialConfigOptions.TenantId);
        var authContext = new AuthenticationContext(authority);
        X509Certificate2 certificate = default;using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser, OpenFlags.ReadOnly))
        {
            var certificateCollection = store.Certificates.Find(X509FindType.FindBySubjectName, credentialConfigOptions.CertificateName, false);
            if (certificateCollection.Count > 0)
            {
                certificate = certificateCollection[0];
            }
        };
        
        var clientAssertionCertificate = new ClientAssertionCertificate(credentialConfigOptions.AppId, certificate);
        AuthenticationResult token = await authContext.AcquireTokenAsync(appId, clientAssertionCertificate);
        return token?.AccessToken;

Now I have to use PEM cert type instead of pfx cert type so I am getting issues while converting PEM format to X509Certificate2. How can I generate access token with PEM certificate?


Solution

  • If you use Net 5.0, we can directly create X509Certificate2 with a cert and key with method X509Certificate2.CreateFromPemFile(<certpath>,<keypath>). For more details, please refer to here.

    If you use other versions, we can create an X509Certificate2 with cert file then import private key with method CopyWithPrivateKey. At last we create Certificate with code new X509Certificate2(pubKey.Export(X509ContentType.Pfx)). For more details, please refer to here.