csrf前端代码写一下
时间: 2024-05-14 09:12:56 浏览: 20
在前端代码中,可以使用以下方式来防止跨站请求伪造(CSRF)攻击:
1. 在表单中添加隐藏字段,该字段包含一个令牌(token),该令牌是服务器端随机生成的,并且每次请求都不同。
```html
<form action="/submit-form" method="POST">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<!-- other form fields -->
<button type="submit">Submit</button>
</form>
```
2. 使用 AJAX 请求发送数据时,在请求头中添加 X-CSRF-Token 字段,该字段的值为服务器端随机生成的令牌。
```javascript
$.ajax({
url: '/submit-data',
type: 'POST',
data: { /* form data */ },
headers: {
'X-CSRF-Token': '{{ csrf_token }}'
},
success: function(response) {
// handle success
},
error: function(xhr, status, error) {
// handle error
}
});
```
3. 设置 HTTP-only 的 cookie,该 cookie 包含一个令牌,该令牌是服务器端随机生成的,并且每次请求都不同。在发送请求时,将该 cookie 自动添加到请求头中。
```javascript
// set cookie when page is loaded
document.cookie = `csrf_token=${csrf_token}; HttpOnly`;
// send request with cookie
fetch('/submit-data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include', // include cookie in request
body: JSON.stringify({ /* form data */ })
})
.then(response => {
// handle response
})
.catch(error => {
// handle error
});
```