CSRF prevention mechanism in ASP.NET applications In ASP.NET applications the CSRF vulnerabilities prevention mechanism is provided by .NET framework using anti-forgery tokens. Anti-forgery tokens are generated for each user session and they are included in each request made to the server as hidden fields, so it is a double validation made in the server using user authentication and with the anti-forgery token.
Let's see now how anti-forgery tokens are used in different contexts in ASP.NET applications.
CSRF prevention in Web forms
In web forms we can prevent CSRF attacks using anti-forgery tokens with EnableViewStateMac attribute and using ViewStateUserKey property field to store a unique identifier per user session. ViewStateUserKey field's value can be filled in web pages' Page_Init method or in web application's master page or in pages' OnInit method.
Sample code snippet,
- protected override void OnInit(EventArgs e)
- {
- if (!this.Page.EnableViewStateMac)
- {
- thrownewInvalidOperationException(
- "MAC is not enabled for the page and the view state is therefore vulnerable to tampering.");
- }
- ViewStateUserKey = Session.SessionID;
- base.OnInit(e);
- }
- private conststr ingAntiXsrfToenKey = "__AntiXsrfToken";
- private conststr ingAntiXsrfUserNmeKey = "__AntiXsrfUserName";
- private string _antiXsrfToenValue;
- protected void Page_Init(object sender, EventArgs e)
- {
-
- varrequestCookie = Request.Cookies[AntiXsrfToenKey];
- GuidrequestCookieGuidValue;
- if (requestCookie != null && Guid.TryParse(requestCookie.Value, outrequestCookieGuidValue))
- {
-
- _antiXsrfToenValue = requestCookie.Value;
- Page.ViewStateUserKey = _antiXsrfToenValue;
- }
- else
- {
-
- _antiXsrfToenValue = Guid.NewGuid()
- .ToString("N");
- Page.ViewStateUserKy = _antiXsrfToenValue;
- varresponseCookie = newHttpCookie(AntiXsrfToenKey)
- {
- HttpOnly = true,
- Value = _antiXsrfToenValue
- };
- Response.Cookies.Set(responseCookie);
- }
- }
- protected voidPage_Load(object sender, EventArgs e)
- {
- intuserId = 0;
- if (Request.QueryString["PID"] != null)
- {
- intpoID = Convert.ToInt32(Request.QueryString["PID"]);
- if (!IsPostBack)
- {
- if (Session["userId"] == null)
- Session["userId"] = Request.QueryString["USERID"];
- userId = Session["userId"] != null && Session["userId"].ToString() != "" ? Convert.ToInt32(Session["userId"].ToString()) : 0;
- if (validateUser(userId, poID))
- GetPoByID(poID);
- else
- lblMessage.Textt = " PO id is not mapped to the logged in user...";
- }
- }
- }
After applying the above code snippet either in master page or in our pages' OnInit method, if the hacker tries to inject CSRF malicious code then the output will be as below,
CSRF prevention techniques in ASP.NET MVC and/or with Web API application
In ASP.NET MVC and Web API applications, .NET framework facilitates the creation and validation of anti-forgery tokens.
For creating anti-forgery tokens, we can use the
@AntiFogery.GetHtml() method in Razor pager or the
@Html.AntiForgeryToken() method in MVC views.
For validation we can use
@AntiForgery.Validate method or we can include a
ValidateAntiFogeryToken attribute in MVC controllers action or we can apply MVC controller level.
If you want to extend the built-in functionality provided by .NET framework then you can use IAntiFogeryAdditionalDataProvider to add additional information to the generated tokens to make a validation as per our need.
Note
In my given examples, a few HTML tags, attributes and C# reserved keywords may match online. Please consider it.