Vapor CSRF

Vapor CSRF

I've just released a new Vapor library - Vapor CSRF. It provides a simple way to protect websites and web forms from CSRF attacks. The project I'm currently working on is the first (very) large project I've done in Vapor 4 so I'm spinning little parts of either into open source libraries like this one or interesting blog posts!

CSRF Attacks

A CSRF (or cross-site request forgery) attack in simple terms is where an attacker tricks a user into making requests that a web application accepts. Imagine a bank website that has a POST request to transfer money into an account. If a malicious site can force the user to send that POST request (when they're logged in) then an attacker could trick a user into transferring money.

CSRF tokens protects against this by ensuring the POST request is legitimate. The website provides a token to the GET request which is then checks when handling the POST request to ensure it matches.

There are other protections you can add to your site as well to mitigate this type of attack. One of the recent protections is SameSite cookies. This is where the browser won't present a site's cookie unless the referrer request has come from the same site. In practice this is more complicated to implement with a good user experience as it has the habit of making it appear like your users aren't logged in when they first visit your site. However it's still a worthwhile protection to investigate adding. Note that not all browsers (especially older ones) support the SameSite attribute.

The CSRF library

The Vapor CSRF library aims to provide a really simple solution using the common technique of CSRF tokens. When you make a GET request to a form, you provide a unique token to be submitted with the form. In the POST request you verify that the CSRF token is provided and matches the expected value. In Vapor this translates to a single call to generate and save a CSRF token to provide to your HTML forms and either a middleware or single call to verify the token.

Check out the GitHub repo for usage details. And feel free to open PRs and issues, I've already had someone offer to write a custom Leaf tag to add the CSRF token as a hidden form input!