12

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.

Brice Williams
  • 588
  • 1
  • 4
  • 9

7 Answers7

19

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.

Garrett Vlieger
  • 9,354
  • 4
  • 32
  • 44
  • 1
    Thanks. You confirmed my suspicion that this was cookie related so I did a lot of trial and error and found this was caused by another WIF secured web application (on another server) creating a WIF cookie with a path of / that apparently was trying to be decrypted by this web application. I fixed this by adjusting the path values used by both applications. Oddly enough I was only seeing this error with IE and not Firefox/Chrome. I'll have to spend some more time with this to better understand the issue. – Brice Williams Nov 23 '11 at 00:37
  • I've run into the same thing. Glad you got it worked out. I'm not sure why you would only see this in IE, but changing the cookie path should be the fix. – Garrett Vlieger Nov 23 '11 at 15:07
  • I had the same problem after I accidentally deleted my local website. Deleting the wif and asp.net cookies did the trick. – Mike Cheel Jul 22 '14 at 17:42
  • 1
    Ran into the same issue after changing my load balancer to point at a different environment. Clearing my cache resolved the error. – TabsNotSpaces Jul 21 '20 at 17:23
7

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

Alex Cherkasov
  • 192
  • 2
  • 9
  • 1
    The Application_Error global handler seems to be the appropriate place. Something along the lines of `var exc = Server.GetLastError();` `if (exc is CryptographicException || exc.InnerException is CryptographicException)` `{ Server.ClearError(); ResetAuthentication(); }` worked for me. – achekh May 18 '12 at 17:13
3

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>

Victor
  • 31
  • 3
2

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>
Community
  • 1
  • 1
1

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();
jcs
  • 611
  • 2
  • 9
  • 22
0

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.

0

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

Nikhil Dinesh
  • 3,359
  • 2
  • 38
  • 41