Search code examples
asp.net-mvc-3securitycsrf

Should I use HTTP referrer validation or token verification to prevent CSRF attacks?


I read about how to protect my web site from CSRF attacks in an ASP.NET MVC web application. They mentioned two ways to do so, either by:

  1. using Token Verification by using <@Html.AntiForgeryToken()> and [ValidateAntiforgeryToken]

  2. using HTTP referrer validation such as:

    public class IsPostedFromThisSiteAttribute : AuthorizeAttribute
        {
        public override void OnAuthorize(AuthorizationContext filterContext)
            {
            if (filterContext.HttpContext != null)
                {
                if (filterContext.HttpContext.Request.UrlReferrer == null)
                    throw new System.Web.HttpException("Invalid submission");
                if (filterContext.HttpContext.Request.UrlReferrer.Host !=
                    "mysite.com")
                    throw new System.Web.HttpException
                        ("This form wasn't submitted from this site!");
                }
            }
        }
    

    and

    [IsPostedFromThisSite]
    public ActionResult Register(…)
    

So I got confused about whether I should use both of them to protect my web site from CSRF attacks or whether I can select one of these methods?


Solution

  • Checking the referrer is problematic. First of all, the HTTP specification specifically allows for clients to not send referrer strings (for various privacy reasons). So, some of your clients may not include it. Second, referrer strings can be spoofed, where an attacker of sufficient skill can make them look like what they need to be in order to carry out a successful CSRF attack.

    Using a CSRF validation token is a stronger approach and is the preferred method of mitigiation against CSRF attacks. You can read about why this is on the OWASP CSRF Cheat Sheet.

    I will also point out that there is no reason why you cannot do both. A Defense-In-Depth (DiD) strategy is usually desirable, so that an attacker would need to defeat multiple, independent, defenses to execute a successful attack. You could implement a weak-referrer-checking approach (IF a referrer is provided by the client, make sure it is what it should be before acting on the request; if the referrer is not present, proceed as if it were present and correct) along with a CSRF validation token. That way, you check the referred information if the client provides it while still making use of the stronger validation token approach.