Asp.Net CSRF
Step 1: Add this code in master page, if there is no master page than add it in page.
//This is code is to generate the random token
protected void Page_Init(Object sender, EventArgs e)
{
if (!IsPostBack)
{
var pageName = Path.GetFileName(HttpContext.Current.Request.Url.AbsolutePath);
var pageToken = pageName + "_ID";
RandomNumberGenerator rng = new RNGCryptoServiceProvider();
var tokenData = new byte[32];
rng.GetBytes(tokenData);
var token = Convert.ToBase64String(tokenData);
Session["token"] = token.Trim();
CSRFToken.Value = pageToken.Trim() + token.Trim();
}
}
Step:2 Verify the token on each post(Add,Update,Delete button event)
protected void btnAddUpdate_Click(object sender, EventArgs e)
{
var pageToken = Path.GetFileName(HttpContext.Current.Request.Url.AbsolutePath) + "_ID";
pageToken = pageToken + Session["token"];
if (CSRFToken.Value.Trim() != pageToken.Trim())
{
Session.Abandon();
Session.Clear();
Response.Redirect("Error.aspx");
//LogOut of the Application
}
else
{
Your Code
}
}
Step 1: Add this code in master page, if there is no master page than add it in page.
//This is code is to generate the random token
protected void Page_Init(Object sender, EventArgs e)
{
if (!IsPostBack)
{
var pageName = Path.GetFileName(HttpContext.Current.Request.Url.AbsolutePath);
var pageToken = pageName + "_ID";
RandomNumberGenerator rng = new RNGCryptoServiceProvider();
var tokenData = new byte[32];
rng.GetBytes(tokenData);
var token = Convert.ToBase64String(tokenData);
Session["token"] = token.Trim();
CSRFToken.Value = pageToken.Trim() + token.Trim();
}
}
Step:2 Verify the token on each post(Add,Update,Delete button event)
protected void btnAddUpdate_Click(object sender, EventArgs e)
{
var pageToken = Path.GetFileName(HttpContext.Current.Request.Url.AbsolutePath) + "_ID";
pageToken = pageToken + Session["token"];
if (CSRFToken.Value.Trim() != pageToken.Trim())
{
Session.Abandon();
Session.Clear();
Response.Redirect("Error.aspx");
//LogOut of the Application
}
else
{
Your Code
}
}
Comments
Post a Comment