DEV Community

Discussion on: Using .pfx and .cer for security in .Net

Collapse
 
albingorkhali profile image
Albin Gorkhali

Praneet, Great article. I have a question on using pfx.

I am using power BI embedded on the on premises intranet app and to get the authentication token, I am using Certificate. The issue i am facing is, when doing locally it works fine. But when posting to our Dev server, it is working on one instance but not on others like QA or UAT environment on premises.

what could be the reason for this? is it because we are not using the certificate properly? wierd thing is if it is failing, why is it working fine for just one instance of webserver and not other webservers?

*Here is the code snippet we are using for getting the authentication token:*

        var tenantSpecificURL = AuthorityUrl.Replace("common", Tenant);
        var authenticationContext = new AuthenticationContext(tenantSpecificURL);
        AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
        var certificatepath = AppDomain.CurrentDomain.BaseDirectory + @"App_Data\SFA.pfx";
        var xCert = new X509Certificate2(certificatepath, "XXXXXXX", X509KeyStorageFlags.PersistKeySet);
        var credential = new ClientAssertionCertificate(ApplicationId, xCert);

        //this is where i believe it is failing
        authenticationResult = authenticationContext.AcquireTokenAsync(ResourceUrl, credential).Result;

        //End of Authentication
        string AccessToken = null; //
        var m_tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
        string Token = "";

This is the error I am getting.

ExceptionMessage":"Invalid provider type specified.\r\n","ExceptionType":"System.Security.Cryptography.CryptographicException","StackTrace":" at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)\r\n at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)\r\n at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()\r\n at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)\r\n at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()\r\n at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.get_PrivateKey()\r\n at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.GetAsymmetricAlgorithm(String algorithm, Boolean privateKey)\r\n at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform.SigningHelper.SignWithCertificate(String message, X509Certificate2 certificate)\r\n at

Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.d__59.MoveNext()"}

.net powerbi x509certificate