08 April, 2009

Sharepoint Access Exception for elevated privileges

Working with FBA I encountered the most bazaar issue. I want my FBA user that is not Admin to be able to update their profile details both their name and email address. SO this works perfectly well when I want to update the DB but the issue comes when I want to update the SPUser account of that user.

I tried many different solutions, Allowing Anonymous Access on both the web and the site and also impersonating the user. In the end the solution which is not that obvious was to disable the FormDigest. Found in this msdn thread.

Here is my final code solution : Prior to this i make sure that this code only executes when the user is non admin

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(this.Site.ID))
{

site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb())

{
SPWebApplication webApp = web.Site.WebApplication;
bool formDigest = webApp.FormDigestSettings.Enabled;
webApp.FormDigestSettings.Enabled = false;


web.AllowUnsafeUpdates = true;
SPIisSettings usersettings = Utils.GetFBAIisSettings(site);
SPUser spUpdateuser = web.AllUsers[usersettings.MembershipProvider + ":" + userName];
if (spuser != null)
{
spUpdateuser.Email = txtEmail.Text;
spUpdateuser.Name = txtFullName.Text;
spUpdateuser.Update();
}
webApp.FormDigestSettings.Enabled = formDigest;
}
}
}
);

No comments: