Used to check for browser translation.
用于检测浏览器翻译。
ブラウザの翻訳を検出する

Defend against CSRF attacks


Overview#

Cross-Site Request Forgery (CSRF) is a type of attack. Attackers induce victims to visit a malicious website and, without the victim's knowledge, send forged requests to a trusted website. These requests will utilize the credentials of the user's current authenticated session, thereby allowing the attacker to exploit the user's identity and permissions to carry out destructive operations such as changing account information, deleting data, etc.

Precondition#

  • Developers with basic programming skills.

Access#

In order to defend against csrf attacks, we provide interface defense measures at both the front end and back end:

  • @blocklet/sdk: provides a csrf middleware for the backend to validate csrf token. The system will only handle the relevant requests normally after passing the validation successfully.
  • @blocklet/js-sdk: Provides the createAxios, createFetch function, carrying csrf token when sending requests.

Backend#

@blocklet/sdk provides the express middleware for the backend to validate csrf.

Basic Usage#

By default, the middleware exported by @blocklet/sdk will intercept all side-effectful APIs (such as POST, PUT requests) and validate their placeholders for validity.

If verification fails, an error will be thrown: Current request status is abnormal, please retry later.

import { csrf } from '@blocklet/sdk/lib/middlewares';

app.use(csrf());

Advanced usage#

In some cases, we may need to allow certain requests based on business logic. In such cases, we can achieve this by customizing the verifyToken function for CSRF token.

import { csrf } from '@blocklet/sdk/lib/middlewares';

app.use(
csrf({
verifyToken: async (req, res) => {
const needVerifyToken = ...;
if (needVerifyToken) { // only need to verify in certain cases
await res.locals.verifyToken(req, res);
}
},
})
);

front end#

@blocklet/js-sdk provides createAxios , createFetch function, which carries csrf token while sending requests.

Basic Usage#

The exported `createAxios` function from `@blocklet/js-sdk` will carry `csrf token` to the request header before sending (side-effectful) requests in the frontend. The backend middleware of the user will verify the token in `csrf token`, and only after successful verification, the request will be processed.

import { createAxios } from '@blocklet/js-sdk';

const api = createAxios({}); // It can also be createFetch

// when making a request, the csrf token will be automatically included in request.headers['x-csrf-token']
await api.put(...);

After successful access, you will be able to see the csrf-token in the request header, just like this:

image.png

Use other front-end request libraries#

import { getCSRFToken } from '@blocklet/js-sdk';

// Send the request with the CSRF token in the header.
request.headers['x-csrf-token'] = getCSRFToken();
你获得 0 积分