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')
}
});
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With