CSRF Tokens and You

tinkerjoegit

Tinkerjoe-Git

Posted on May 3, 2021

CSRF Tokens and You

Cross-site request forgery

CSRF deals with a web security vulnerability that would allow an attacker or unauthenticated third party to manipulate data in malicious ways to exploit unprotected web applications.

Largely the stakes are not particularly high in our cushy environment at flatiron, but dealing with CSRF in the professional world is going to be expected. Depending on what market you're dealing with, the stakes can certainly go sky high if a malicious party manipulates financial information.

Lets go through the basics. The CSRF token will be a unique token embedded in your sites HTML. When a user makes a POST request, the token is sent along with the request. In a rails environment, the token will be compared with the one stored in cookies for the authenticity.

Lets go to our application_controller.rb. Where we are going to enable this functionality.

protect_from_forgery with: :exception
Enter fullscreen mode Exit fullscreen mode

Let's get our meta tags in order on our application.html.erb

<%= csrf_meta_tags %>
Enter fullscreen mode Exit fullscreen mode

bear in mind, if you're using bootstraps or copying in an existing template, your tags may be already within the header section.

You won't see the actual token contents in your IDE when its running. Instead go to your localhost http://127.0.0.1:3000 and right click and hit "Inspect". Now we're in our DevTools, in the header section you'll see the actual contents of the generated token. This can be relevant to debugging when you're getting invalid POST errors. Next up on our POST view forms, inside the

<form> 
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
</form>
Enter fullscreen mode Exit fullscreen mode

along with the rest of your form code, you'll want this, you'll in-fact need this. Largely you're all set-up, there's way more stuff going on under the hood, but this is a great place to start.
Caveat! if you're doing a

form_with(model: url: exmaple_path) do |f|
Enter fullscreen mode Exit fullscreen mode

Rails is magically taking care of that hidden field token for you.

💖 💪 🙅 🚩
tinkerjoegit
Tinkerjoe-Git

Posted on May 3, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024