Monday, 31 March 2008

Form Digest and SPSecurity.RunWithElevatedPrivileges

A colleague of mine recently had an issue when running code using SPSecurity.RunWithElevatedPrivileges. The SPWeb's AllowUnsafeUpdates attribute had been set to true but an error was still occuring when calling methods that checked the FormDigest of the current page.

I found an article that said the answer to this is to disable the FormDigest settings on the web application using

SPSite.WebApplication.FormDigestSettings.Enabled = false

This means that when the form digest is validated it will always report that it is valid. My opinion on this though is that it isn't very safe. If you're creating a page that runs code under elevated privileges the last thing you want to do is introduce the ability to bypass form digest.

The Solution
That was when I discovered that the form digest is only validated once per request and then a flag is set in the page's context. Therefore, if you call the ValidateFormDigest method on the SPWeb object. This can easily be done using


This will validate the form digest and cache the result ensuring that when the ValidateFormDigest is called within the SPSecurity.RunWithElevatedPrivileges wrapper it will always validate.

This solution means that FormDigest on the page will not be comprimised and the code will still run. You will still need to set AllowUnsafeUpdates to true.

Also for a bit of fun I decided to see if it was possible to run the entire page under elevated privileges. I'm not sure if you'd ever want to do this but this is what I came up with. Execute entire page with elevated privileges

1 comment:

dodysw said...

Wow, this magical 1 liner solve my problem. With SPUtility.ValidateFormDigest(), I don't even have to disable the FormDigestSettings.

Thanks Steve!