Pages

Tuesday, June 10, 2014

SharePoint Programming - Dont set or use AllowUnsafeUpdates Instead Use ValidateFormDigest

Generally in your daily SharePoint Programming, you may come across issue of 

The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again

To Fix this issue, if you googled many places it will be suggested as to set AllowUnsafeUpdates = true or false.

If you do above, it will not throw error and resolve the issue but it is not the right way. By setting AllowUnsafeUpdates you are allowing for security threats.

The best way is to use SPUtility.ValidateFormDigest()
  • In your Master Page or in your aspx page, place below tag
         <sharepoint:formdigest id=”FormDigest1″ runat=”server” />
  • Now in your .cs file, in your init method or before you use the SPSecurity.RunWithElevatedPrivileges, place below code line.
protected override void OnInit(EventArgs e)
{
if (Page.IsPostBack)
{
SPUtility.ValidateFormDigest();
base.OnInit(e);
}
}

                                          [OR]

SPUtility.ValidateFormDigest();
SPSecurity.RunWithElevatedPrivileges(delegate()
{....

No comments:

Post a Comment