Wednesday, February 15, 2012

Windows Azure and ACS - CryptographicException: Key not valid for use in specified state

My technical architect asked me to work on windows Azure access control service and configure ACS for ADFS. After following all the steps on Azure management portal such as configuring identity provider, adding relying party; it was time for me to add STS reference in my azure web role. If you don’t know click - how to add STS reference.
I added the STS reference in my web role and pressed F5 to start debug. And I got difficult exception mentioned below –
CryptographicException: Key not valid for use in specified state.
InvalidOperationException: ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details). If you are using IIS 7.5, this could be due to the loadUserProfile setting on the Application Pool being set to false.
 I don’t understand why I always face very odd issues. Anyways, following is the description about solution to the above mentioned error.
By default when we say Add STS reference, we are talking about Windows Identity foundation. WIF is configured to use DPAPI to encrypt your cookies which won’t work in Azure applications. This occurs because the DPAPI stores the key data in user profiles. If the profile is not loaded, DPAPI won’t be able to perform the decryption. This would mean that a cookie created by one server (or  web role instance in case of Azure) would not be readable by another server or web role instance. To solve this problem you should use a cookie encryption mechanism that uses a key shared by all the web role instances. To overcome this problem we have to use RsaEncryptionCookieTransform to encrypt your cookies instead of DPAPI. WIF training kit has an excellent lab which shows how you can use it. Link is as follows - http://msdn.microsoft.com/en-us/gg557891
Look for point number 23. It shows what code we need to use to overcome key not valid problem. So with respect to above mentioned link, I wrote following code in my global.asax.cs file –
protected void Application_Start(object sender, EventArgs e)
{
FederatedAuthentication.ServiceConfigurationCreated += new EventHandler<Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs>(FederatedAuthentication_ServiceConfigurationCreated);
}

And the event handler method in global.asax.cs is as follows –
void FederatedAuthentication_ServiceConfigurationCreated(object sender, Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs e)
{
List<CookieTransform> sessionTransforms =
        new List<CookieTransform>(new CookieTransform[] {
        new DeflateCookieTransform(),
        new RsaEncryptionCookieTransform(e.ServiceConfiguration.ServiceCertificate),
        new RsaSignatureCookieTransform(e.ServiceConfiguration.ServiceCertificate)  });
            SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
            e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler);
}
Above code directs application to read certificate present in <serviceCertificate>
Tag present in web.config file. When you add STS reference from ACS configured ADFS; by default <serviceCertificate> tag gets commented as shown below –
<!--Commented out by FedUtil-->
<!--<serviceCertificate><certificateReference x509FindType="FindByThumbprint" findValue="82581E2E0215…A527717FAF2C6A" storeLocation="LocalMachine" storeName="My" /></serviceCertificate>-->

So uncomment <serviceCertificate> tag. Now above statement says that, find the respective certificate in LocalMachine – My store. So you need to add the respective certificate in My store of local machine. When you open Run window – and type “certmgr.msc”; certificate store for CurrentUser is opened and not for LocalMachine is opened. So make sure that you must add certificate in Local machine My store. For detailed steps click - adding certificate in LocalMachine my store.
 Also make sure that, you need to add same certificate in ACS on azure management ACS portal under “Certificates and Keys” menu – “Service Namespace” Type X.509 Certificate as shown below –

Once this is done, key not valid issues should disappear.
Hope this helps.
Cheers…
Happy Cryptographication!!!
Top rated windows Azure and ACS errors and their solutions -
ID1024 - The configuration property is not valid.

No comments:

Post a Comment