Urgent.News

What's breaking now, across thousands of outlets.

Tech

Como proteger sua aplicação frontend contra ataques CSRF

Sabe o que é e como se proteger de ataques CSRF (Cross-Site Request Forgery) ? CSRF é um tipo de ataque no qual um usuário autenticado é induzido a executar uma ação que não pretendia realizar em uma aplicação. Imagine, por exemplo, que você está logado em um site de compras e recebe um e-mail contendo um link aparentemente inofensivo. Ao acessar esse link, uma página maliciosa tenta realizar uma…

Cross-Site Request Forgery (CSRF) is a type of attack where an authenticated user is tricked into executing an unintended action on a web application. For instance, if a user is logged into a shopping site and clicks on a seemingly harmless link, a malicious page can attempt to perform an action on the site the user is already authenticated on.

If the application lacks proper protection mechanisms, the browser may automatically send the user's authentication cookies, allowing the operation to be executed as if it were requested by the user.

There are several ways to reduce the risk of such attacks. This article focuses on the use of CSRF tokens, with an emphasis on the communication between the frontend and backend.

A CSRF token is not the same as the token used for user authentication or session maintenance. While authentication tokens, session cookies, or access tokens identify the user and control their access to the application, CSRF tokens serve a different purpose: helping the server verify if a request that modifies data was indeed initiated by the legitimate application.

To prevent CSRF attacks, one widely known approach is to use tokens. The server generates a random and unpredictable value, associates it with the user's session, and makes it available to the application. When the frontend performs an operation that changes the application's state, such as POST, PUT, PATCH, or DELETE, it also sends the CSRF token. The backend checks this token before allowing the operation to be executed.

The flow can be represented as follows:

Server generates the token → Frontend receives the token → Frontend sends the token in the request → Backend validates the token → Request is accepted or rejected

It's important to note that GET, HEAD, and OPTIONS requests typically do not need to use CSRF tokens, as they should not perform operations that alter data in the application.

Implementing CSRF tokens in JavaScript involves several steps:

1. Generate the CSRF token on the server. The token should be generated using a cryptographically secure source of randomness. Math.random() should not be used for security-related tokens. In a Node.js application, for example:

```javascript

import crypto from "crypto";

function generateCSRFToken() {

return crypto.randomBytes(32).toString("hex");

}

```

This code generates a 256-bit random token. The server must also have a way to validate this token later, usually by associating it with the user's session.

2. Make the token available to the frontend. A server-rendered application can make the token directly available in the HTML:

```html

<meta name="csrf-token" content="TOKEN_GENERATED_BY_SERVER" />

```

On the frontend, JavaScript can retrieve the token:

```javascript

const csrfToken = document.querySelector('[name="csrf-token"]').getAttribute("content");

```

Alternatively, in single-page applications (SPAs), a specific CSRF cookie can be used. The architecture adopted depends on the strategy used by the application.

3. Send the token in requests. For applications using AJAX or APIs, it's common to send the token through a custom HTTP header. Using Axios, for example:

```javascript

import axios from "axios";

const csrfToken = document.querySelector('[name="csrf-token"]').getAttribute("content");

axios.post("/api/cart/add", { productId: 123, quantity: 1 }, {

headers: {

"Content-Type": "application/json",

"X-CSRF-Token": csrfToken,

},

});

```

In this example, the frontend obtains the token from the server, and a POST request is sent to /api/cart/add. The token is sent through the X-CSRF-Token header. The backend validates this value before processing the operation.

Although placing the CSRF token in URLs or query strings is possible:

```

/api/cart/add?csrfToken=TOKEN

```

it's not recommended, as it can cause the token to appear in logs, browser histories, analytics tools, or other intermediary systems.

Validating the CSRF token on the backend is crucial, as having the token on the frontend alone does not provide protection. An example of validating the token in a simplified backend flow:

```javascript

app.post("/api/cart/add", (req, res) => {

const csrfToken = req.headers["x-csrf-token"];

if (!validateCSRFToken(req.session, csrfToken)) {

return res.status(403).json({

message: "CSRF token invalid",

});

}

// Proceed with the operation

});

```

By following these steps, developers can help protect their web applications against CSRF attacks.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

Prices round up, discounts round down, and one package decides both

Munchable Premium is £10 a month. The price list has 24 currencies in it, and the rule the whole thing is built around is that the number you read is the number your card is charged.

  • Munchable Premium charges fixed prices in local currency
  • Prices rounded up via two-step process with conversion fee buffer
  • Discounts rounded down using mid-market rate

Deferred Deep Links in React Native: Complete Integration Guide

If you've shipped a React Native app, you've probably wired up universal links / app links already. Existing users tap a link, the OS hands it to your app, Linking.addEventListener fires, you push the…

  • Deferred deep linking preserves link context when app is not installed
  • Integration guide uses LinkTrail SDK for React Native apps
  • Handle both installed and first-time installs the same in router

Kram: A Tiny macOS Tool for Taming Chaotic Folders

I Built Kram: A File Organizer That Knows What Not to Touch My Downloads folder had become a crime scene. Hundreds of files. Random screenshots. ZIP archives. PDFs. DMGs. Old projects.

  • Kram is a macOS file organization tool
  • Categorizes files by type into sensible folders
  • CLI-first tool with future features in development

More from Saturday 26 September →