Search code examples
securitycookieswebcsrfmeta-tags

Why CSRF token should be in meta tag and in cookie?


What's the need of to put CSRF token name and value inside <head> tag using <meta> like:

e.g:

<meta content="authenticity_token" name="csrf-param" />
<meta content="4sWPhTlJAmt1IcyNq1FCyivsAVhHqjiDCKRXOgOQock=" name="csrf-token" />

I've read about concept to keep CSRF value in cookie but does not find about why to keep inside <head> tag.


Solution

  • To prevent CSRF you need a value that is submitted with the request that cannot be sent by a malicious site. Authentication cookies are not suitable because if an attacker can make the browser send a request to the victim site, the cookies will automatically be submitted.

    For example, by submitting a form via JavaScript contained on www.evil.com to attack the user's session on www.example.com:

    <form method="post" action="https://www.example.com/executeAction">
        <input type="hidden" name="action" value="deleteAllUsers">
    </form>
    
    <script>document.forms[0].submit()</script>
    

    Storing an anti CRSF token within the page is the OWASP recommended solution for preventing another website from submitting the form, as the random token in the user's session cannot be read by www.evil.com due to the Same Origin Policy preventing JavaScript on www.evil.com reading the page content of www.example.com.

    These tokens can be stored anywhere within the page. Most commonly it will be within hidden form fields, but they could also be stored within HTML 5 data- attributes. It seems like using meta tags is simply another way it can be stored where the JavaScript can include it in any form submissions the page makes.