I'm working on improving the security of my company's website and wanted to create a token to prevent forgery attempts that could be easily maintained this is what I came up with.
public class AntiForgeryToken
{
private readonly string _referenceToken;
public AntiForgeryToken()
{
_referenceToken = Guid.NewGuid().ToString();
}
public string ReferenceToken
{
get { return _referenceToken; }
}
}
In my base class for my MasterPage I have a HiddenField wrapped with property named: ReferenceToken
protected virtual void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
InjectToken();
}
ValidateToken();
}
private void InjectToken()
{
var token = ObjectFactory.GetInstance<AntiForgeryToken>();
ReferenceToken = token.ReferenceToken;
}
private void ValidateToken()
{
var token = ObjectFactory.GetInstance<AntiForgeryToken>();
if (ReferenceToken.Equals(token.ReferenceToken, SC.InvariantCultureIgnoreCase))
return;
...do stuff for failed token
}
I have StructureMap handle storing the token inside the Session so it's persisted per user session, would all of this be a valid implementation of an AntiForgery scheme?
Edit: There seems to be some confusion on my question, yes I understand ASP.NET MVC has a built in AntiForgeryToken scheme, this question is explicitly about how to recreate this for WebForms to prevent the usage of a CSRF attack (Cross Site Request Forgery). I understand this in no means removes the need for proper authorization of user rights.
I was going to bring up the very link that @Neal and @solairaja posted: Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper. This article explains more of what the CSRF attack is and how MVC stops it however their solution isn't applicable to webforms which is why I went about implementing my own.
After seeing the response from @Neal I think that will most likely be the accepted answer since I didn't realize I could just get the actual source code from the MVC tool which will most likely replace the guid creation. But I'll leave the question open incase anyone else has some valuable information to add.