Wednesday 7 September 2011

Adding some security in our forms in Sharepoint 2010 and FormDigest

After completing our nice form and deploy it into our Sharepoint site we try to run it and we get this beautiful error:

The security validation for this page is invalid

Well, What can I say?, the frustation of this issue sometimes is quite wide, especially because you are dealing with ASP.NET and that is not related with Sharepoint objects. Anyway let’s go to see what is happening. This is our code:

<form id="Form1" method="post" runat="server">
   <asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 282px; POSITION: absolute; 
      TOP: 282px" runat="server" Text="Button"></asp:Button>
</form>

Right… everything seems to be ok there, every single bit… but Sharepoint is asking for something else, and that is security. Sharepoint want us to add a security validation within the form of the .aspx page, How? buy adding this line:


 <SharePoint:FormDigest runat="server"/>

The class FormDigest will be the one in charge of doing this, so the original code should look like this now:


 <SharePoint:FormDigest runat="server"/><form id="Form1" method="post" runat="server">
   <SharePoint:FormDigest runat="server"/>
   <asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 282px; POSITION: absolute; 
      TOP: 282px" runat="server" Text="Button"></asp:Button>
</form>

 


Before we finish with this issue I would like to add a remark from Microsoft that it could be quite useful in the future:To make posts from a Web application that modify the contents of the database, you must include the FormDigest control in the form making the post. The FormDigest control generates a security validation, or message digest, to help prevent the type of attack whereby a user is tricked into posting data to the server without knowing it. The security validation is specific to a user, site, and time period and expires after a configurable amount of time. When the user requests a page, the server returns the page with security validation inserted. When the user then submits the form, the server verifies that the security validation has not changed.