gpt4 book ai didi

python - POST 请求不适用于 token 验证检查

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

使用flask_jwt_extended,每当我尝试使用以下装饰器发送POST请求时:

@jwt_refresh_token_required
@jwt_required

我有这个 401 错误:
{
"msg": "Missing CSRF token"
}

当我使用 GET 时,它工作正常。
我已经阅读了关于双重提交保护的文档,但这并不能解决我的问题。 有什么想法可以解决我的问题吗?
重现问题的代码如下。

下面是我的代码结构:
- src/__init.py__ # where I put all configs
- src/auth.py # where are the endpoints

init.py

login_serializer = URLSafeTimedSerializer(SERIALIZER_SECRET_KEY)
jwt = JWTManager()


def create_app():
app = Flask(__name__)
app.config["SECRET_KEY"] = SERIALIZER_SECRET_KEY
app.config['JWT_SECRET_KEY'] = JWT_SECRET_KEY
app.config['JWT_TOKEN_LOCATION'] = ['cookies']
app.config['JWT_COOKIE_CSRF_PROTECT'] = True
db.init_app(app)
jwt.init_app(app)

# blueprint for auth routes in our app
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)

# blueprint for non-auth parts of app
from .routes import main as main_blueprint
app.register_blueprint(main_blueprint)

return app

授权文件

import logging
from flask import Blueprint, request, current_app as app, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from . import login_serializer, jwt
from flask_jwt_extended import (jwt_required, jwt_refresh_token_required,
get_jwt_identity, get_raw_jwt, unset_jwt_cookies,
current_user, create_access_token, create_refresh_token, set_access_cookies, set_refresh_cookies)

auth = Blueprint('auth', __name__)


def set_response_cookies(token_identity, resp=None, token_types=["access", "refresh"]):
"""
Helper function to set cookies in response
"""
logging.warning("Setting cookies")
resp = jsonify(resp)
token_types.sort()
if token_types == ["access", "refresh"]:
access_token = create_access_token(identity = token_identity)
refresh_token = create_refresh_token(identity = token_identity)
if not resp:
resp = jsonify({"access_token": access_token, "refresh_token": refresh_token})
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)
return resp
elif token_types == ["access"]:
access_token = create_access_token(identity = token_identity)
if not resp:
resp = jsonify({"access_token": access_token})
set_access_cookies(resp, access_token)
return resp
elif token_types == ["refresh"]:
refresh_token = create_refresh_token(identity = token_identity)
if not resp:
resp = jsonify({"refresh_token": refresh_token})
set_refresh_cookies(resp, refresh_token)
return resp
else:
raise ValueError("Wrong Call to this function")


@jwt.user_claims_loader
def add_claims_to_access_token(identity):
"""
"""
return {
'email': identity
}


@jwt.user_loader_callback_loader
def user_loader_callback(identity):
"""
Ignore Here, but I use it to get a User object (not mentionned here) from a Token.
"""
return User.objects(
email=identity,
).first()


@auth.route('/token', methods=['POST'])
def token_post():
""" obj =
{"email": "email", "password": "password"} => Tokens
"""
obj = request.get_json()
resp = set_response_cookies(obj["email"], {"token": True}, ["access", "refresh"])
return resp, 200


@auth.route('/token/access', methods=['POST'])
@jwt_refresh_token_required
def refresh_access_cookies():
if current_user:
resp = set_response_cookies(current_user.email, {"token_refreshed": True}, ["access"])
return resp, 200

所以,在这里,我所要做的就是重现错误:
  • 发出 POST 请求/token => 在 postman 中,我的回复将获得所有 cookie 和标题。
  • 发出 POST 请求/ token /访问 => 给出上面提到的错误。
  • 最佳答案

    在您的配置中,您启用了 JWT_COOKIE_CSRF_PROTECT为真。
    出于开发目的,如果您可以将其设置为可能不安全的 False,则该错误将消失。
    在生产中,您需要在请求 header 上传递 csrf_token。
    我认为这个链接可以帮助你。
    https://flask-jwt-extended.readthedocs.io/en/stable/tokens_in_cookies/ (见最后一节)
    https://flask-wtf.readthedocs.io/en/stable/csrf.html

    关于python - POST 请求不适用于 token 验证检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62119272/

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