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')
}
});
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.