flask總結05(在 Flask 項目中解決 CSRF 攻擊)

一:安裝 flask_wtf

pip install flask_wtf

二:設置應用程序的 secret_key,用於加密生成的 csrf_token 的值

# session加密的時候已經配置過了.若是沒有在配置項中設置,則以下:
app.secret_key = "#此處能夠寫隨機字符串#"

三:導入 flask_wtf.csrf 中的 CSRFProtect 類,進行初始化,並在初始化的時候關聯 app

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

四:在表單中使用 CSRF 令牌:

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

 

五:scrf的過程理解

代碼顯示方法不被容許的代碼html

#manage.pyflask

  
from flask import Flask, render_template, request, g
from settings.dev import DevConfig
from flask.ext.wtf import CSRFProtect

app = Flask(__name__, template_folder="templates", static_folder="static")
app.config.from_object(DevConfig)

CSRFProtect(app)

# @app.route("/csrf_test", methods=["get", "post"])
@app.route("/csrf_test")
def index():
    if request.method == "GET":
        return render_template("form.html")

    else:
        print(request.form)

        return "ok"

if __name__ == "__main__":
    app.run()
View Code

templates下的form.htmlsession

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>csrf案例</title>
</head>
<body>
    <form action="" method="post">
        帳號:<input type="text" name="username"><br><br>
        密碼:<input type="password" name="password"><br><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>
View Code

運行後顯示的結果是:app

而後修改manage.py中的代碼,添加ide

@app.route("/csrf_test", methods=["get", "post"])

代碼以下:post

from flask import Flask, render_template, request, g
from settings.dev import DevConfig
from flask.ext.wtf import CSRFProtect

app = Flask(__name__, template_folder="templates", static_folder="static")
app.config.from_object(DevConfig)

CSRFProtect(app)

@app.route("/csrf_test", methods=["get", "post"])
def index():
    if request.method == "GET":
        return render_template("form.html")

    else:
        print(request.form)

        return "ok"

if __name__ == "__main__":
    app.run()
View Code

再次執行:而且提交:加密

說明須要在html文檔中添加:csrf_tokenspa

<input type="hidden" name="csrf_token" value="{{csrf_token()}}">

修改後的代碼是:3d

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>csrf案例</title>
</head>
<body>
    <form action="" method="post">
        <input type="hidden" name="csrf_token" value="{{csrf_token()}}">
        帳號:<input type="text" name="username"><br><br>
        密碼:<input type="password" name="password"><br><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>
View Code

運行後的結果顯示:code

相關文章
相關標籤/搜索