Using CSRF Tokens

Intro

Cross-Site Request Forgery (CSRF) is a security vulnerability where an attacker tricks a user into performing unwanted actions on a web application. CSRF tokens help prevent this by adding a unique, unpredictable value to web forms, which the server validates upon form submission.

In this tutorial, you'll learn how to implement CSRF protection in your web applications using Wappler.

NOTE: CSRF tokens are currently only available for NodeJS

Server Side

The first thing we need to do is to enable the CSRF security protection in Server Connect. Open the Server Connect panel and open its global options:

Open the CSRF tab:

And enable CSRF protection:

A notification, which explains that if you enable this option, you will need to add CSRF tokens or a global meta tag to all your forms appears. Click Yes:

You can see there is an excluded methods option. The CSRF protection should be implemented for all state-changing methods such as POST, PUT, DELETE, and PATCH. We recommend leaving the default values there:

Click Save:

And we are done. The next we need to do is to add the CSRF tokens on the pages, where your forms are.

Client Side

There are two methods of adding CSRF protections on your pages - using a global meta tag on or adding a hidden CSRF input in each of your forms.
When your page includes either the meta tag or the hidden input, App Connect will automatically send a special header with each form submission. If neither the meta tag nor the hidden input is present, the form submission will fail, returning an error, and no further actions will be executed.

Using a Global Meta Tag

Using a global meta tag on the layout page is the easiest way to add the protection to all your pages.
When the meta tag is used it generates a new CSRF token and session on each page request. So if you don't want this to happen, just use the other method - using a hidden input in each form.

Open your layout page and add a new meta tag:

Select CSRF Token

And click the dynamic data picker for the meta tag:

In the data picker select CSRF Token under Functions:

And you are done:

A CSRF Token will be generated when a page is loaded.

Using a Hidden Form Input

The other method of protecting your forms is to add a special hidden input.
Open a page containing a form that posts some data. Add new element inside the form:

Select CSRF Token Hidden Input:

Click the dynamic data picker to select a value for this hidden input:

And select the CSRF Token under Functions:

Save your page:

And you are done. Do this for all your forms, which you want to add CSRF protection to.

10 Likes

I will just speak your "language" brother...
:+1: :beer:

1 Like