Protecting Applications from CSRF attacks with Ruby on Rails

Construction workers with protective hats
Construction workers with protective hats

What is a CSRF Attack?

Protecting against CSRF attacks with the Rails App

Here’s what it looks like in practice:

onSubmit(event) {
event.preventDefault();
const url = "/api/v1/dogs/create";
const { name, owner, age} = this.state;

if (name.length == 0 || owner.length == 0 || age.length == 0)
return;

const body = {
name,
owner,
age
};

const token = document.querySelector('meta[name="csrf-token"]').content;
fetch(url, {
method: "POST",
headers: {
"X-CSRF-Token": token,
"Content-Type": "application/json"
},
body: JSON.stringify(body)
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Bad network response");
})
.then(response => this.props.history.push(`/dog/${response.id}`))
.catch(error => console.log(error.message));
}

Written by

Full-Stack Software Engineer, Designer, and salsa dancer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store