Welcome
Getting Started
How to Guides
Application vs Blocklet
Create Blocklet
Compose Blocklets
Develop Blocklet
User and Passport
Communicate with DID Wallet
Blocklet Storage
Using Blocklet Preferences
Build blocklet for profit [deprecated]
Bundle your blocklet
Manage Blocklet Versions
Publish your blocklet to the world
Deploy your blocklet
Read/Write blockchain in blocklet
Operation and maintenance your blocklet
Reference Guides
Conceptual Guides
Frequently Asked Questions
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 trusted websites. These requests will use the credentials of the user's current authenticated session, allowing the attacker to exploit the user's identity and permissions to perform destructive operations such as changing account information, deleting data, etc.
Preconditions#
- Developers with certain programming foundations
access#
In order to defend against csrf
attacks, we provide interface defense on both the front end and back end:
- @blocklet/sdk:为后端提供了
csrf
中间件,用于验证csrf token
。只有在成功通过验证后,系统才会正常处理相关请求。 - @blocklet/js-sdk:为前端提供了
createAxios
,createFetch
函数,在发送请求的时候携带csrf token
。
back-end#
@blocklet/sdk 为后端提供了 express
的 csrf
中间件,用于验证 csrf token
。
Basic Usage#
By default, the middleware exported by @blocklet/sdk will intercept all side-effectful interfaces (such as POST, PUT requests) and validate that their placeholders are valid.
If the 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 which case we can implement this by customizing the verifyToken function of the csrf token.
import { csrf } from '@blocklet/sdk/lib/middlewares';
app.use(
csrf({
verifyToken: async (req, res) => {
const needVerifyToken = ...;
if (needVerifyToken) { // 只在某些情况下才需要校验
await res.locals.verifyToken(req, res);
}
},
})
);
Front end#
@blocklet/js-sdk 为前端提供了 createAxios
,createFetch
函数,在发送请求的时候携带 csrf token
。
Basic Usage#
@blocklet/js-sdk 导出的 createAxios
函数,会在前端发送(含有副作用的)请求之前携带 csrf token
到请求头中。
import { createAxios } from '@blocklet/js-sdk';
const api = createAxios({}); // 也可以是 createFetch
// 请求的时候会自动携带 csrf token 到 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: