Brice Williams
Brice Williams

Reputation: 578

Microsoft.IdentityModel: Key not valid for use in specified state

I have a claims aware web application using Windows Identity Foundation that has been working well, except on one server. I am seeing the error message shown below in the event log.

Exception information: 
    Exception type: CryptographicException 
    Exception message: Key not valid for use in specified state.

   at System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope)
   at Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded)

This application is using a very standard implemenation of WIF with ADFS v2. It is not using RsaEncryptionCookieTransform. I am looking for any suggestions on how to diagnose this. Things I have tried so far:

  1. The Application Pool is using the ASP.NET v4.0 identity which has the "Load User Profile" setting set to true.
  2. I deleted the C:\Users\ASP.NET v4.0\AppData folder and saw this was successfully recreated.
  3. I checked permissions on certificate private keys, which were good. I also tried disabling token encryption which did not make any difference.

Any advice would be appreciated.

Upvotes: 12

Views: 51133

Answers (7)

Nikhil Dinesh
Nikhil Dinesh

Reputation: 3409

This issue is because of insufficient permission. The app pool should have ApplicationPoolIdentity Identity to make it work. Goto your apppool -> Advanced Settings -> Build-in accounts to change the settings

Upvotes: 0

Michael Goldshmidt
Michael Goldshmidt

Reputation: 141

The following worked for me:

You need to add section to system.identityModel/identityConfiguration

Reference: SessionSecurityTokenHandler trying to decrypt SessionSecurityToken in RSA-encrypted cookie using DPAPI; why?

  <system.identityModel>
    <identityConfiguration saveBootstrapContext="true">
      <audienceUris>
        <add value="yoursite.com" />
      </audienceUris>
      <issuerNameRegistry type="Thinktecture.IdentityModel.Tokens.MetadataBasedIssuerNameRegistry, Thinktecture.IdentityModel">
        <trustedIssuerMetadata issuerName="urn:federation:company:stage" metadataAddress="https://federation-sts-stage.company.com/FederationMetadata/2007-06/FederationMetadata.xml"></trustedIssuerMetadata>
      </issuerNameRegistry>
      <certificateValidation certificateValidationMode="None" />
<securityTokenHandlers>
     <add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler,  
             System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

      <remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, 
            System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </securityTokenHandlers>
    </identityConfiguration>
  </system.identityModel>

Upvotes: 2

Victor
Victor

Reputation: 31

I resolve my case because i have the same cookie name "FedAuth" for two applications (this is the name by default). Just put a different name and it's resolve :

<system.identityModel.services>
<federationConfiguration>
  <cookieHandler name="ACookieName" />
</federationConfiguration>

Upvotes: 3

jcs
jcs

Reputation: 639

Deleting the FedAuth cookies might work. When the exception occurs, try this in the Application_Error method of the Global.asax file:

Microsoft.IdentityModel.Web.FederatedAuthentication.SessionAuthenticationModule.SignOut();

Upvotes: 1

user1431276
user1431276

Reputation: 11

This error doesn't seem to be caught by http application. Please check out http://social.technet.microsoft.com/wiki/contents/articles/1898.aspx#Q1 instead.

Upvotes: 0

Alex Cherkasov
Alex Cherkasov

Reputation: 192

The issue is 100% reproducible:

Indeed, after application being re-deployed, AND old authentication cookie is left on the client machine (client did not sign out) -this error appears to the client on any following request. To fix this error client either has to delete the cookies and/or sign-in then sign-out from STS. Once all done - the error goes away and everything is fine until next upgrade....

After some research, I think this is a bug in the SessionAuthenticationModule that needs to be fixed. If you carefully look at the stack trace above, there is an interesting method called TryReadSessionTokenFromCookie, which sets expectation that authentication module will "try" to read the token from cookie, and will return false if this fails -here is the code (thanks to Resharper!):

public bool TryReadSessionTokenFromCookie(out SessionSecurityToken sessionToken)
{
    byte[] sessionCookie = this.CookieHandler.Read();
    if (sessionCookie == null)
    {
        sessionToken = null;
        return false;
    }
    sessionToken = this.ReadSessionTokenFromCookie(sessionCookie);
    if (DiagnosticUtil.TraceUtil.ShouldTrace(TraceEventType.Verbose))
    {
        DiagnosticUtil.TraceUtil.Trace(TraceEventType.Verbose, TraceCode.Diagnostics, SR.GetString("TraceValidateToken", new object[0]), new TokenTraceRecord(sessionToken), null);
    }
    return true;
}

Obviously, the code fails in this method with unhandled error and developer is left without any option to handle the error in more or less reasonable way. (...Or at least I could not find any, since this HTTP module does not pass this error onto HttpApplication object for handling, and throws it in the user's face.) So, I think there are two bugs: 1) Security token handler needs to be more specific on the reasoning of thrown ID1073 (server side decryption error or wrong (old) cookie error) 2) There has to be a way for a developer to handle this error and sign-out the user, if it occurs. I'll take ANY help on this one... Can anyone PLEASE create a sample code, showing how to intercept this exception so user can be automatically signed-out when this error occurs? Again, Application.Error event does not seem to get fired from this module -not sure what else can be done to handle it, other than writing my own SessionAuthenticationModule. ANY HELP IS HIGHLY APPRECIATED!!! Thanks! Alex

Upvotes: 7

Garrett Vlieger
Garrett Vlieger

Reputation: 9494

This is usually caused by the application not being able to decrypt the authentication token cookie. Make sure that the identity that owns the App Pool has sufficient permission to access your certificate store. Try changing the Identity to NetworkService and see if that helps.

You should also clear your browser's cookies to make sure you don't have cookies from a different application cached.

Upvotes: 19

Related Questions