gpt4 book ai didi

python - Flask JWT 扩展缺少 csrf 访问 token

转载 作者:行者123 更新时间:2023-12-03 08:13:54 25 4
gpt4 key购买 nike

我的 Flask 应用程序使用 JWT 作为身份验证手段。这些 token 存储在 cookie 中,并且 Flask-jwt-extended 配置为使用它们。对于常规 GET 请求,身份验证工作正常,并且 @jwt_required 装饰器能够从 cookie 中读取 token 并对用户进行身份验证。但是,当使用 fetch() 发出 AJAX POST 请求时,扩展程序无法读取它们并返回 Missing CSRF token 错误。奇怪的是,当访问 POST 路由中的请求对象时,所有必需的 cookie 都存在,并且在经过身份验证时所有其他路由中都存在,这意味着 fetch() 正确设置了所有必需的 cookie:

ImmutableMultiDict([
('csrftoken', 'valid_csrf_token'),
('session','valid_session_cookie'),
('access_token_cookie', 'valid_access_token'),
('csrf_access_token', 'valid_csrf_access_token')
])

Flask POST 路由:

@main.route("/sendmail", methods=["POST"])
@jwt_required()
async def send_mail():
data = json.loads(request.data)

mail_template = render_template("mail-view.html", data=data)

pdf_report = pdfkit.from_string(mail_template, False)

message = Message(
subject="Flask-Mailing module",
recipients=["<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcced9dfd9ccd5d9d2c891d1ddd5d0fcd8d3d1ddd5d292dfd3d1" rel="noreferrer noopener nofollow">[email protected]</a>"],
body="Message body",
subtype="html",
)
message.attach("report.pdf", pdf_report)
await mail.send_message(message)
return jsonify({"message": "success"}), 200

获取请求:

fetch(window.location.origin + "/sendmail", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: "same-origin",
body: JSON.stringify(mail),
})

我的应用程序配置对象:

class DevConfig:
SECRET_KEY = os.environ.get("SECRET_KEY")
JWT_SECRET_KEY = os.environ.get("JWT_SECRET_KEY")
JWT_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
JWT_TOKEN_LOCATION = ["cookies"]
JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(hours=1)

MAIL_SERVER = "smtp.googlemail.com"
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USE_SSL = False
MAIL_USERNAME = os.environ.get("MAIL_USERNAME")
MAIL_PASSWORD = os.environ.get("MAIL_PASSWORD")
MAIL_FROM = os.environ.get("MAIL_USERNAME")

最佳答案

使用flask-jwt-extended默认设置,仅需要为状态更改请求方法(除“GET”之外的所有方法)发送CSRF-Token。这就是为什么即使没有 CSRF token ,“GET”方法也会被授权。其次,CSRF-Token 的整体思想是网络浏览器不会自动发送它,因此它不会在 cookie 中被接受:

By default, we accomplish this by setting two cookies when someonelogging in. The first cookie contains the JWT, and encoded in that JWTis the double submit token. This cookie is set as http-only, so thatit cannot be access via javascript (this is what prevents XSS attacksfrom being able to steal the JWT). The second cookie we set containsonly the same double submit token, but this time in a cookie that isreadable by javascript. Whenever a request is made, it needs toinclude an X-CSRF-TOKEN header, with the value of the double submittoken. If the value in this header does not match the value stored inthe JWT, the request is kicked out as invalid.

https://flask-jwt-extended.readthedocs.io/en/stable/token_locations/

因此,每当您发送请求时,都应该将 CSRF-Token 添加到 header 中:

fetch(window.location.origin + "/sendmail", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-TOKEN": getCookie("csrf_access_token"),
},
credentials: "same-origin",
body: JSON.stringify(mail),
})

关于python - Flask JWT 扩展缺少 csrf 访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70071418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com