question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

MSAL Upgrade: AcquireTokenForClientAsync System.Security.Cryptography.CryptographicException : Key not valid for use in specified state

See original GitHub issue

Which Version of MSAL are you using ? 2.7.0

Platform Azure App Service, (webjob), dot net classic 4.7.

What authentication flow has the issue?

  • Desktop / Mobile
    • Interactive
    • Integrated Windows Auth
    • Username Password
    • Device code flow (browserless)
  • Web App
    • Authorization code
    • OBO
  • Web API
    • OBO
    • Application only with certificate

Is this a new or existing app? c. This is a new app or experiment I originally started with MSAL and had to downgrade to ADAL to workaround the issue.

Repro

var cac = new ClientAssertionCertificate(certProvider.AppCertificate); //your x509 certificate loaded in via the current user/my store, loaded in the azure web app SSL settings
var clientCredentials = new ClientCredential(cac);
var app = new ConfidentialClientApplication(clientId, $"https://login.microsoftonline.com/{tenantName}.onmicrosoft.com", "https://daemon", clientCredentials, new TokenCache(), new TokenCache());
var result = await app.AcquireTokenForClientAsync(new List<string> { $"{applicationUrl}/.default" });

Expected behavior The code to execute properly, especially since it works when debugging locally.

Actual behavior Getting the following exception

Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.ProcessQueueMessage ---> System.Security.Cryptography.CryptographicException : Key not valid for use in specified state. at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) at System.Security.Cryptography.Utils._ExportKey(SafeKeyHandle hKey,Int32 blobType,Object cspObject) at System.Security.Cryptography.RSACryptoServiceProvider.ExportParameters(Boolean includePrivateParameters) at System.Security.Cryptography.RSA.ToXmlString(Boolean includePrivateParameters) at Microsoft.Identity.Client.Platforms.net45.NetDesktopCryptographyManager.GetCryptoProviderForSha256(X509Certificate2 certificate) at Microsoft.Identity.Client.Platforms.net45.NetDesktopCryptographyManager.SignWithCertificate(String message,X509Certificate2 certificate) at Microsoft.Identity.Client.ClientAssertionCertificate.Sign(String message) at Microsoft.Identity.Client.Internal.Jwt.JsonWebToken.Sign(ClientAssertionCertificate credential,Boolean sendCertificate) at Microsoft.Identity.Client.Internal.Requests.AuthenticationRequestParameters.ToParameters() at async Microsoft.Identity.Client.Internal.Requests.RequestBase.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters,CancellationToken cancellationToken) at async Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.ExecuteAsync(CancellationToken cancellationToken) at async Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken) at async Microsoft.Identity.Client.ConfidentialClientApplication.AcquireTokenForClientCommonAsync(IEnumerable`1 scopes,Boolean forceRefresh,ApiIds apiId,Boolean sendCertificate) at async Microsoft.Identity.Client.ConfidentialClientApplication.AcquireTokenForClientAsync(??) at async SiteCreationSharePoint.ProvisioningService.GetClientContext(String sharePointUrl,String applicationUrl)

Additional context/ Logs / Screenshots The equivalent code with ADAL works

 var authority = $"https://login.windows.net/{tenantId}/";
 var authContext = new AuthenticationContext(authority);
 var host = new Uri(sharePointUrl);
 var resourceId = host.Scheme + "://" + host.Host + "/";
 var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certProvider.AppCertificate);
 var result = await authContext.AcquireTokenAsync(resourceId, clientAssertionCertificate);

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:9 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
baywetcommented, Jul 9, 2019

@henrik-me thanks for the follow up. Upgraded to 4.1.0 and it seems to be working properly so far.

1reaction
baywetcommented, Feb 6, 2019

@henrik-me : yes the only changes between the working and non-working scenario are ADAL => MSAL and the changes in code I mentionned. I do have the project on my end, if you can’t repro, let me know if you need me to clean it up and put it somewhere.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why am I getting a "Key not valid for use in specified state ...
When attempting to run the log in sequence on another machine I get an exception/error: Key not valid for use in specified state....
Read more >
Office 365 - How to fix Microsoft.Graph.ServiceException ...
Symptom: Activities inside Office 365 scope fail with Microsoft.Graph.ServiceException “Key not valid for use in specified state”.
Read more >
Key not valid for use in specified state Error with Windows ...
Recently, while installing an MSI file, I have encountered a problem that installer can not install the software and it posts an error...
Read more >
Dynamics 365 – Key not valid for use in specified state
ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details).
Read more >
netFramework/Microsoft.Identity.Client.xml 3.2.0
If an authority was not specified at the application level, ... are bound to the HTTP request and to a cryptographic key, which...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found