> For the complete documentation index, see [llms.txt](https://close.gitbook.io/yun-wei-bi-ji/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://close.gitbook.io/yun-wei-bi-ji/python/flask/flask-xiang-mu-zhong-jie-jue-csrf-gong-ji.md).

# Flask 项目中解决csrf攻击

首先装个库吧，命令如下:

```
pip install flask_wtf
```

在 Flask 中， Flask-wtf 扩展有一套完善的 csrf 防护体系，对于我们开发者来说，使用起来非常简单

1. 设置应用程序的 secret\_key，用于加密生成的 csrf\_token 的值

```html
# 1. session加密的时候已经配置过了.如果没有在配置项中设置,则如下:
app.secret_key = "#此处可以写随机字符串#"

# 2. 也可以写在配置类中。
class Config(object):
    DEBUG = True
    SECRET_KEY = "dsad32DASSLD*13%^32"
    
"""加载配置"""
app.config.from_object(Config)
```

1. 导入 flask\_wtf.csrf 中的 CSRFProtect 类，进行初始化，并在初始化的时候关联 app

```python
from flask.ext.wtf import CSRFProtect
CSRFProtect(app)
```

1. 在表单中使用 CSRF 令牌:

```html
<form method="post" action="/">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
</form>
```

视图代码:

```python
from flask import Flask, render_template, request
from flask_wtf import CSRFProtect

app = Flask(__name__, template_folder='templates')
csrf = CSRFProtect(app)
app.config["SECRET_KEY"] = '223223qwq'


@app.route('/')
def index():
    data = {}
    return render_template('index5.html', **data)


@app.route('/login', methods=["POST"])
def login():
    print(request.form)
    # ImmutableMultiDict([('csrf_token', 'IjcwYWE0YjU3MmY5OWU4MzczNTM2MWJiNjc4NTQ0NjE4MTA2MzliMjAi.X7pChg.dH_NdAfCArZLJSPL8RMrJGc2Lqs'), ('username', ''), ('password', '')])
    return 'ok'


if __name__ == '__main__':
    app.run(debug=True)
```

模板代码:

```html
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="{{ url_for('login') }}" method="post">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" >
        账号: <input type="text" name="username" value=""><br><br>
        密码: <input type="password" name="password" value=""><br><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/python/flask/flask-xiang-mu-zhong-jie-jue-csrf-gong-ji.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
