Wednesday, March 30, 2016

System.Security.Cryptography.CryptographicException: Error occurred during a cryptographic operation.

Problem:
I have an MVC 5 project using ADFS on prem as user control.  The application works fine but at some point after running for a few minutes I start getting the Crypto error.  The only left to do to recover is to kill all IE sessions and restart the web app.  This is still in staging so not a prod problem yet.




Solution:
This is an issue with the machine key.  If you do not specify it in configuration then it gets created with each new version of the app you publish.  The work around is to catch the error.  This can be done in the Global.asax.  The application Error event traps the error.  Once this happens we force a signout and clear the error.  The app will then force the a reauthentication "automagically".  This should prevent the user from seeing the failure.


// Be sure to reference System.IdentityModel.Services
// and include using System.IdentityModel.Services;
// at the start of your class
protected void Application_Error(object sender, EventArgs e)
{
    var error = Server.GetLastError();
    var cryptoEx = error as CryptographicException;
    if (cryptoEx != null) {
        FederatedAuthentication.WSFederationAuthenticationModule.SignOut();
        Server.ClearError();
    }
}






Source
  1. http://stackoverflow.com/questions/25857577/error-occurred-during-a-cryptographic-operation-when-decrypting-forms-cookie
  2. http://stackoverflow.com/questions/14119965/federated-authentication-on-azure

No comments:

Post a Comment