Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to store the csrf token in meta tag?

If I make a POST request without using form and want to prevent CSRF attack, what I can do is to set the csrf-token in meta tag and put it back to the header when the request is triggered. Is it a good practice?

<meta name="csrf-token" content="xxx">

Put the token back via the header, using JQuery for example:

$.ajaxSetup({
   headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   }
});
like image 382
tony.0919 Avatar asked Apr 16 '15 16:04

tony.0919


People also ask

Is it safe to store CSRF token in cookie?

CSRF tokens should not be transmitted using cookies. CSRF tokens in GET requests are potentially leaked at several locations, such as the browser history, log files, network appliances that log the first line of an HTTP request, and Referer headers if the protected site links to an external site.

What is CSRF token in meta tag?

CSRF tokens normally go in a form as hidden form fields. Putting them in a meta tag only makes sense if you are using JavaScript. JavaScript could read the tokens from the meta tag and post them to an action.

Should CSRF token be secure?

CSRF tokens should contain significant entropy and be strongly unpredictable, with the same properties as session tokens in general. You should use a cryptographic strength pseudo-random number generator (PRNG), seeded with the timestamp when it was created plus a static secret.

Can CSRF token be stolen?

Stealing Anti-CSRF Tokens: When CSRF tokens are passed as cookie parameters without Secure and HTTPOnly flags, an attacker can potentially steal the CSRF token via XSS or other attacks.


1 Answers

Yes, this is a good practice if you are using AJAX. You could also put the token inside of the form (which is more convenient if submitting the whole form), but if you are using AJAX, it just needs to go somewhere to grab it.

Inside a hidden field or a meta tag are both very good options.

like image 178
ajon Avatar answered Oct 08 '22 22:10

ajon