After reading this article you will know:

  • What CSRF is
  • How to protect your application from CSRF

Cross-Site Request Forgery (CSRF) is an attack that forces an (end) user to execute unwanted actions on a web application in which they're currently authenticated. It is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the web application trusts.

Want to know more about CSRF? Take a look at Cross-Site Request Forgery (CSRF)

You can add a csrf_tag to your form to protect it. The tag generates a hidden <input> tag with a specific token that will be sent to the POST to identify the POST request. This CSRF token ensures that the POST request came from your application, and not any other website or app.

Enable CSRF protection

To enable CSRF protection on your website you will have to check the Enable CSRF (Cross-Site Request Forgery) checkbox on your POST webpage to enable the CSRF protection. This will force the application to only accept requests done from a trusted environment: In our case, your Betty Blocks web application.

After this is checked you will have to add the following liquid tag to your HTML form:

{{ csrf_tag }}

Adding this tag to a HTML form should look something like this:

<form method="post" action="/posts">
  {{ csrf_tag}}
  <div class="form-group">
    <label for="email">Email:</label>
    <input type="email" class="form-control" name="email">
  </div>
  <div class="form-group">
    <label for="username">Username:</label>
    <input type="text" class="form-control" name="username">
  </div>
  <div class="form-group">
    <label for="description">Description:</label>
    <textarea class="form-control" name="description" rows="3"> .        </textarea>
  </div>
  <button class="btn btn-primary">Create</button>
</form>

If you don't place the tag in your HTML form you will most likely get the following error:

Invalid CSRF (Cross Site Forgery Protection) token, make sure all requests include a '_csrf' param

If you do have the correct setup and still receive this message, you can try to log out and back in again in order to reset the token.

Did this answer your question?