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.

"Key not valid for use in specified state" - happens in .Net Framework 4.7.2 only, not on .Net Core 2.2

See original GitHub issue

Which Version of MSAL are you using ? Microsoft.Identity.Client Version=3.0.8

Platform

my library in .Net Core and a web job console in .Net Framework 4.7.2

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

Other? - please describe;

Is this a new or existing app?

C. This is a new app or experiment

Repro

            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
            connectionStringBuilder.DataSource = this.Settings.DataSource;
            connectionStringBuilder.InitialCatalog = this.Settings.InitialCatalog;
            connectionStringBuilder.Encrypt = this.Settings.Encrypt;
            connectionStringBuilder.TrustServerCertificate = this.Settings.TrustServerCertificate;

            SqlConnection connection = new SqlConnection(connectionStringBuilder.ConnectionString);
            connection.AccessToken = this.Settings.TokenAuthenticator.GetAccessTokenAsync(DefaultScope).Result;

        public async Task<string> GetAccessTokenAsync(IEnumerable<string> scopes)
        {
            X509Certificate2 certificate = this.GetCertificate();
            ConfidentialClientApplicationOptions option = new ConfidentialClientApplicationOptions
            {
                AzureCloudInstance = this.CloudInstance,
                ClientId = this.ApplicationId,
                TenantId = this.TenantId,
            };
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
                .CreateWithApplicationOptions(option)
                .WithCertificate(certificate)
                .Build();

            AuthenticationResult result = await app.AcquireTokenForClient(scopes)
                .ExecuteAsync();

            return result.AccessToken;
        }

Expected behavior No exception. I should be able to authenticate a connection to my Azure SQL Database. I have run the same code on .Net Core console project, and it has been working.

Actual behavior I got this exception in my .Net Framework 4.7.2 console project: Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.PollBuilds —> System.AggregateException: One or more errors occurred. —> 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.Internal.JsonWebToken.Sign(ClientAssertionCertificateWrapper credential, Boolean sendCertificate) at Microsoft.Identity.Client.Internal.Requests.ClientCredentialHelper.CreateClientCredentialBodyParameters(ICoreLogger logger, ICryptographyManager cryptographyManager, ClientCredentialWrapper clientCredential, String clientId, AuthorityEndpoints endpoints, Boolean sendX5C) at Microsoft.Identity.Client.Internal.Requests.RequestBase.<SendTokenRequestAsync>d__22.MoveNext() — End of stack trace from previous location where exception was thrown — at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.<ExecuteAsync>d__2.MoveNext() — End of stack trace from previous location where exception was thrown — at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.Internal.Requests.RequestBase.<RunAsync>d__14.MoveNext() — End of stack trace from previous location where exception was thrown — at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.<ExecuteAsync>d__3.MoveNext() — End of stack trace from previous location where exception was thrown — at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Scm.Authentication.Settings.ClientCertificateSettings.<GetAccessTokenAsync>d__12.MoveNext() — End of inner exception stack trace — at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task1.get_Result() at Scm.Authentication.AzureDatabaseBase.CreateConnection()

Possible Solution

Additional context/ Logs / Screenshots Add any other context about the problem here, such as logs and screebshots. Logging is described at https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/logging

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:14 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
jmprieurcommented, Jul 10, 2019

I agree @henning-krause We need to improve the exception to have a meaningfull and actionable message that the certificate should be exportable.

1reaction
jmprieurcommented, Jul 5, 2019

@henrik-me, @MarkZuber, @bgavrilMS We might want to provide a better error message when the certificate is not exportable? Or do we need to use the X509KeyStorageFlags.EphemeralKeySet flag ? to avoid the exception?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Troubleshoot .NET Framework targeting errors
To resolve the error, make sure that your application targets a .NET version that's compatible with the version that's targeted by the projects ......
Read more >
Getting Error "Key not valid for use in specified state."
I tried to find this error on internet, but not getting any correct solution. Looking for a perfect one. c# · encryption ·...
Read more >
Error "Key not valid for use in specified state"
The problem seems to be linked with the installation of the .NET Framework 1.1 SP1 Hotfix KB867460. After running the rsactivate and rskeymgmt ......
Read more >
Using .NET Standard with Full Framework .NET - Rick Strahl
Runtime implementations are specific versions of a .NET Runtime such as .NET 4.6.1 or 4.7.2, .NET Core 2.2, Xamarin.IOs 10, Mono 5.18 etc....
Read more >
.NET Framework version history - Wikipedia
Microsoft started development on the .NET Framework in the late 1990s originally under the name of Next Generation Windows Services (NGWS).
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