Home > Back-end >  Do I need to use csrf protection if I am not using form tags?
Do I need to use csrf protection if I am not using form tags?

Time:07-26

I am making some forms to apply for membership in an organization. I haven't used form tag and it's just a bunch of inputs (strings, selects, and checks) and the information is sent through ajax for a Flask server. It's this safe? I am not using forms so I am not sure how to handle the csrf value

CodePudding user response:

The Problem

Consider some malicious website which all it does is:

window.onload = function() {
  var body = {
    action: "payment", amount: 500
  }
  $.ajax("https://your-api.com", body)
}

So if you are logged in your site and visit this page, a request on your behalf would be made, successfully.

The Solution

To mitigate this, add a csrf parameter, only known to your server and the pages it serves. Your rendered HTML pages will look like:

var csrf = "secret-8-digits-value-from-session-of-user";

// and on any request add this param
var body = {
  action: "payment", amount: 500, csrf: csrf
}
$.ajax("https://your-api.com", body)

// now server will verify `csrf` from *request* against `csrf` from *session*
// if no match, then reject the request.

Now you can visit malicious website again. They don't know your session csrf code. So their malicious code will not work because your server would reject the csrf from request.

  • Related