Privacy settings
We use cookies and similar technologies that are necessary to run the website. Additional cookies are only used with your consent. You can consent to our use of cookies by clicking on Agree. For more information on which data is collected and how it is shared with our partners please read our privacy and cookie policy: Cookie policy, Privacy policy
We use cookies to access, analyse and store information such as the characteristics of your device as well as certain personal data (IP addresses, navigation usage, geolocation data or unique identifiers). The processing of your data serves various purposes: Analytics cookies allow us to analyse our performance to offer you a better online experience and evaluate the efficiency of our campaigns. Personalisation cookies give you access to a customised experience of our website with usage-based offers and support. Finally, Advertising cookies are placed by third-party companies processing your data to create audiences lists to deliver targeted ads on social media and the internet. You may freely give, refuse or withdraw your consent at any time using the link provided at the bottom of each page.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

CSRF Token

Looking for a security standard that you can enforce to combat hassles, unverified access, and lethal invasions on key web applications? Try the CSRF token. Capable of checking the genuineness of the client-side request, this distinctive token can keep myriad cyber risks at bay.

CSRF Token

An Overview of CSRF

As CSRF tokens are used to decrease the likelihood of CSRF vulnerability, having a rudimentary knowledge of this cyber threat will allow AppSec experts to learn about the utility of this security measure and how useful it is.

Cross-Site Request Forgery, or better say CSRF, is one of the many cyber risks that the world is currently dealing with. The vulnerability exploits the access privileges of a verified user over a given web-based application.  

To plan this attack, cyberpunks mislead the targeted user in a way that the login credentials are acquired. Mostly, hackers take the help of social engineering to create a situation wherein intended users are forced to make immediate movements like changing the current password or making a payment.

The success of this attack is largely based on the fact the web application saves user cookies that are shared with the server as users make a session request. As cookies often possess crucial login details, exploiting them might help hackers to impersonate a verified user and access the concerned application.

An Overview of CSRF Token

As lessening cyber-attack possibilities remain the priority of every organization, many preventive measures are in place and CSRF token is one such security practice that is used against CSRF attacks. The simplest possible CSRF token meaning is that it is a unique and non-predictable value developed by server-side applications.

Seeing its viability, experts recommend it for every state-modifying request as it can control CSRF and XSS attacks up to a great extent.  

The unmatched protection abilities of CSRF token comes from the distinct entropy they feature. The tokens are auto-generated and have a static value. As tokens are stored in an active session, acquiring them is not that easy for hackers. The seeded timestamp of the token increases its security and makes them more viable against CSRF attacks.

How Does It Work and How Do I Use It?

Every CSRF token has two copies. The first copy remains saved in the server and the second copy is communicated to the client as a hidden field of a web form or as a header of an HTTP request. The token is hard to replicate because it’s secretive and has district features. 

As a client makes an HTTP request and forwards it to the web server, the pre-forwarded CSRF token is part of the client request. As the request is forwarded to the server, it starts comparing the request-side token with the saved server-side token. 

If there is a CSRF token missing or incorrect issue, it’s concluded that the user is verified, and access is granted. If there is any mismatch, the session request is denied.

Generation of CSRF Tokens

While one plans to execute CSRF tokens as a security solution, it’s important to learn that they should feature distinct features and remain have an arbitrary value so that its prediction is not possible.

Keep this in mind, the industry practice suggests taking the help of PRNG or Pseudo Random Number Generator tool. Utilizing the cryptographic technique, PRNG creates unique and time-stamped CSRF tokens.

For improved security, CyberSec professionals can generate a specific token by slightly modifying the PRNG output. However, this demands great skills and time as even a slight change needs to be perfectly implemented and the process will require extracting a solid hash of the entire token structure.

But, the security that it will present is unbeatable. In addition to this, it’s important to ensure that CSEF tokens are disposed of after every use. Reusability is not meant for them. Keep the activation time duration short so that they auto-expire.

Don’t use HTTP GET requests to send CSRF tokens to the user as this request can deliver tokens in URLs and hackers can extract them easily.

Transferring CSRF tokens

Just as generating quality tokens is important, security professionals should ensure that CSRF tokens are transferred securely as well. The ideal CSRF token transferring practices recommend:

  • Employing hidden form field
  • Preferring POST method
  • Placing the field featuring the CSRF token early in HTML
  • Place the token field ahead of the non-hidden field
  • Avoid employing URL query strings for transmission, as this isn’t a safe approach. In general, query strings are logged on myriad client and server-side records and are easily accessible within the browser a client is using to access the internet. They are often known to be transferred to any 3rd part app. Hence, they should be avoided.
  • JavaScript should be used to insert these tokens in the HTTP request header 
  • Performing token validation

CSRF Token Implementation

Let’s learn about CSRF commissioning in different programming language ecosystems like Java, JavaScript, and PHP. Checkout the CSRF token example below:

Implementing the CSRF token in JavaScript

JS supports CSRF protection measures by default. Hence, it’s easy to use CSRF tokens in most of the leading frameworks. One can implement CSRF tokens in JavaScript utilizing csurf, the middleware of Express.js, which is useful for CSRF token validation and construction. Below-stated workflow can help with this goal.

Go to the index.js file and enter the code:

app.get('/', csrfProtection, (req, res) => { res.render('index', { csrfToken: req.csrfToken() });

Once this is done, open the views folder and add the index.ejs file. For this, below mentioned configuration command is useful.

<input type='hidden' name='_csrf' value='<%= csrfToken %>'> <label for='name'> Name:</label> <input type='text' name='name'> <button type='submit'> Update </button> </form>

In this command, the / route extracts the csrfToken variable in the index. ejs template while interpolating the token in a secret field.

As we can see, it’s the /profile route that holds the request and confirms the CSRF validation.

Implementing the CSRF token in Java

While Java is a great programming language, it lacks default protection against CSRF vulnerability. Hence, it’s highly recommended to enforce CSRF tokens while Java is used. The standard industry approach suggests engaging auxiliary classes or filters so that CSRF tokens are created and resource analysis is performed.

Generic Stateless filters are quite famous for this purpose as this is capable of quick and seamless commission of double-submit cookie patterns. Also, this filter promotes CSRF protection as workflows are moved forward.

Before deploying this filter, you need to define it in the web.xml file of the Java application.

<filter> <filter-name>CSRFFilter</filter-name> <filter-class>com.github.adriancitu.csrf.GenericCSRFStatelessFilter</filter-class> <filter> <filter-mapping> <filter-name>CSRFFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

Now, you have two initialization options; csrfHeadername and csrfCookieName. You can choose one according to your ease and preference.

The filter offers a dedicated ExecutionContext class instance for every HTTP request. The filter carefully observes the protection status of the concerned HTTP request. In general, the status is categorized into three sections: 




Based on the output received, the filter takes appropriate actions. For instance, if the status obtained is either of the first two sections, the filter will use the TokenBuilderHook class to generate a CSRF token and its associated cookie.  

But, if the output is the last one, the filter will use ResourceCheckerHook to find out the current status of CSRF protection and delivery a response using ResponseBuilderHook class.

Implementing the CSRF token in PHP

PHP is perhaps the most preferred language for CMS and is the reason behind thousands of dynamically designed websites. Hence, if AppSec professionals want to learn about protecting websites, knowing about PHP implementation is important.

The basic workflow for this procedure is explained below. Begin the process by generating a form footer script of the concerned website’s landing page. This way, you will succeed in invoking SecurityService. This is the PHP class that you need to create the CSRF token for PHP and even evoke a PHP session.

Using this PHP class, you can create CSRF tokens that will validate the request and even load it in a secret field. The customary SecurityService.php configuration is as quoted below.

public function getCSRFToken() { if (empty($this->session[$this->sessionTokenLabel])) { $this->session[$this->sessionTokenLabel] = bin2hex(openssl_random_pseudo_bytes(32)); } if ($this->hmac_ip !== false) { $token = $this->hMacWithIp($this->session[$this->sessionTokenLabel]); } else { $token = $this->session[$this->sessionTokenLabel]; } return $token; }

Using this configuration, one can easily execute CSRF tokens in PHP. Once that’s done, the related contact form’s data is fetched so that details like message, subject, and sender’s details can be noted. Keep in mind that this form stores the token inside a secretive csrf-token.

As you submit the token, the application will start performing the JQuery form validation. Post this submission, the form implements a script whose responsibility is to do a net-to-net comparison of pre-stored and freshly embedded tokens. If a match is found, a user session is granted, and if a CSRF token mismatch is there, the user request will be denied with an error note.

Fixing CSRF Vulnerability In Popular Web Frameworks

CSR threat incidences are on the rise because this enables cyberpunks to gain admin-like access to specific web applications. However, this is not something that enterprises would like to face or deal with. Hence, they need to have an understanding of early and accurate detection and fixation of CSRF token invalid errors or key CSRF vulnerabilities. 

Below is a crisp guide on fixing CSRF vulnerabilities in leading frameworks like Angular, Express, and Django.

  1. CSRF Protection in Django

Django is a Python-based open-source backend framework empowering tons of web applications. As it supports code reusability and multiple plugin supports, it has become a highly renowned framework for modern application development.

It has the edge over other frameworks when it comes to CSRF attack protection, as certain default security measures are offered. For instance, there exists a reliable middleware to safeguard you against CSRF threats. To make sure it is active and protects the apps, the csrf token django should be activated, while the csrf_token tag should be part of the form fields.

  1. CSRF protection in Angular

As Angular comes with the brand tag Google, it is likely to be highly advanced and feasible, and it indeed is. This open-source framework offers specific user interface elements that are compatible with a wide range of platforms and data-driven devices.

As far as its security measures against CSRF attack is concerned, it offers a customary approach that involves reading the CSRF tokens and constructing the custom header for them. The customer header used here is known as ‘X-XESR-TOKEN’.

While this protection does a basic job, you need to make efforts to protect the server-side resources against CSRF, as Angular’s default CSRF protection only works on the client side.

  1. CSRF protection in Express

Express is a world-renowned backend web framework famous because of its speedy and have customization abilities. It works for Node.js and is an open-source framework. It offers very basic functionalities. Hence, no in-built CSRF protection is offered. However, you can use the pluggable middleware, csurf, of Express to deal with CSRF vulnerability.

The great thing about csurf is that it asks bare minimum setup and comes with multiple bootstrap choices. Hence, you can use it easily.

Anti CSRF Tokens

Fix Invalid CSRF Token

Despite taking adequate measures in generating and implementing CSRF tokens, some errors are likely to occur and you might have to face with ‘Invalid CSRF Token’ issue. Here are some of the practice ways to fix this.

  • Prefer custom request headers

As one plans to implement CSRF tokens, minor user interface changes can cause huge problems. This is why one of the best approaches to avoid the ‘Invalid CSRF Token’ hassle is to use customized request headers that are powerful to empower the defense mechanism. With a custom quest header, the same-origin policy comes into action that is famous for discarding all cross-origin requests.

As this happens, strong restrictions like using only JavaScript while enforcing customer and using customer headers only inside the origin.

  • Using pre-built and in-use CSRF mitigation techniques

It’s easy to avoid this error by using the synchronizer token defense that is part of most of the development frameworks. This mechanism is capable of providing overall protection to the application.

To improve the efficacy, it’s important to use this token before you start crafting a custom system. This way, the default defense will manage to provide adequate protection.

  • Bring UI-focused CSRF Defense

Lastly, we recommend using UI-based CSRF defense methods like one-time tokens, CAPTCHA, or reauthentication, as these methods offer highly robust input validation.

CSRF Protection by Wallarm

Organizations that aim to ensure that verified login credentials are not exploited and causing troubles need to ensure that CSRF attacks are nowhere to be seen. CSRF tokens are of great help control a CSRF attack. Just introduce the token in a web application and control or stop the spread of the CSRF threat.

However, to make this possible, organizations need to:

  • Constantly monitor microservices, APIs, and web applications so that targeted applications are identified  
  • Conduct periodic scans so that the vulnerability at its infancy stage
  • Apply strict security measures so that the concerned app remains risk-free even in the future

All these are tedious tasks demanding unwearied attention on every security aspect. This is when the advanced WAAP and API security platform of Wallarm make a difference. Both these solutions allow security-concerned businesses to build fully automated, quick, accurate, and extensive CSRF identification and fixation solutions.

They both are compatible with a wide range of web applications and cloud ecosystems. Instead of using outdated RegEx detection techniques, these advanced security solutions used advanced detection methodology that renders fewer false positive and false negative rates.

Along with CSRF, Wallarm’s WAAP and API security solutions are capable of detecting and resolving a wide range of threats that include credential stuffing, OWASP Top 10 threats, API-specific threats, DDoS attacks, and so on.

Their implementation is hassle-free as they can easily integrate with the current workflow and start protecting immediately. Start using these advanced API and app security solutions and keep your key digital resources.  



Subscribe for the latest news

February 26, 2024
Learning Objectives
Subscribe for
the latest news
Related Topics