Saturday, March 28, 2009

Using Elevated Privileges and AllowSafeUpdates Method - Potential Security Risks

Although not recommended, there may be times when you need your code to perform certain functions that the current user does not have the necessary permissions to perform. I have such situation in one of our project, suppose that you wanted to provide add, edit or delete capability to all users who use your application, regardless of their permissions on the list. So how this would be achieved?

By using the SPSecurity class, it provides a method RunWithElevatedPrivileges that allows you to run a subset of code in the context of an account with higher privileges than the current user. You need to wrap the RunWithElevatedPrivileges method around your code, as shown below: 

    protected void btnAddListItem_Click(object sender, EventArgs e)
    {
        using (SPSite oSite = SPContext.Current.Site)
        {
            // Run with an account with higher privileges than the current user
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    // Turn off security validation
                    oWeb.AllowUnsafeUpdates = true;
                    // Code to add list item to a list
                    SPList oList = oWeb.Lists["ListName"];
                    SPListItem oListItem = oList.Items.Add();
                    oListItem["PostCode"] = txtPostCode.Text;
                    oListItem.Update();
                    // Turn on security validation
                    oWeb.AllowUnsafeUpdates = false;
                }
            });
        }
    }

Also, in certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code. If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.

This is a common mistake when coding using AllowSafeUpdates method, so I think it is worth a mention because not many people knew this.

No comments: