IIS - AddDataProtection PersistKeysToFileSystem no

2019-04-14 16:33发布

问题:

I've developing an asp.net core application to tun on a web far, and I'm using "AddDataProtection" to protect for key encryption at rest like, the documentation recommends, but when I deploy my application and run directly from IIS with AppPool identity, the key is never created and I get errors on the DpapiNG windows logs.

My code is the following:

services.AddDataProtection(opt => opt.ApplicationDiscriminator = ApplicationConfig.dataProtectionApplicationDiscriminator)
            .PersistKeysToFileSystem(new DirectoryInfo(encKeyPath))
            .ProtectKeysWithDpapiNG(string.Format("CERTIFICATE=HashId:{0}", ApplicationConfig.dataProtectionCertThumbprint),
                flags: DpapiNGProtectionDescriptorFlags.None);

Debugging from visual studio, everything runs fine, but I'm running VS under administrator rights, so permission is not an issue here.

I've tried adding permissions to the AppPool App user to the private key it self directly from MMC, but it did not worked, and even gave permission on the full path to the location were the keys should be created like stated here https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview (check first comment) but also it did not worked.

I was only able to make it work by setting the AppPool to run with the identity of an Administrator, but clearly this is a no go, I just wanted to make sure this was a permission issue somewhere.

Is anybody facing the same issue that is able to help?

Regards, André

回答1:

Most likely your issue is you are trying to store your keys somewhere in a folder path that you are cobbling together (or even by using the default path that AddDataProtection provides) that uses an environment path such as %LOCALAPPDATA%. Example: "%LOCALAPPDATA%\ASP.NET\DataProtection-Keys". Usually, by default IIS DOES NOT set up your app pool accounts with environment path variables such as %LOCALAPPDATA%. The value ends up being blank and your app then tries to write keys to the wrong folder (such as \ASP.NET\DataProtection-Keys instead of %LOCALAPPDATA%\ASP.NET\DataProtection-Keys).

Fix: Within %WINDIR%\System32\inetsrv\config\applicationHost.config set setProfileEnvironment=true. I think you have to restart IIS as well.