Python Flask CSRF 令牌给出了意想不到的结果

Python Flask CSRF token is giving unexpected results

我正在尝试实施 csrf,但我对它的工作原理感到困惑。 我的 python 文件。

from flask_wtf.csrf import CSRFProtect, CSRFError
csrf = CSRFProtect()
app = Flask(__name__)
app.config['SECRET_KEY'] = 'FlaskAppKey'
csrf.init_app(app)

我的js文件。

       var csrftoken = "{{ csrf_token () }}";
       $.ajax(
       {
    url: '/calendar_data/',
    dataType:'json',
    type: 'GET',
    contentType: 'application/json',
    data:dataString,
    beforeSend:function(xhr,settings)
    {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },

request.header 转储显示。

X-Csrftoken: IjQ5NjYxOWRiYzgwOWU1N2Q0OWY0MmUxMDRjOGU1ZDcwNGUwNTJkM

如果我删除令牌,网站不会出错。

我有一条错误路线。所以我不确定我是否正确地实施了一切。从代码中删除令牌后,我预计会出现错误。

      @app.errorhandler(CSRFError)
      def handle_csrf_error(e):
  print(e)
  return ''

如果未发送令牌,请求是否会出错?

路线页面

@app.route("/calendar_data/")
def calendar_data():
    stuff
return jsonify(data=data[1])

您可能希望使用 POST 请求进行测试。

这可能不会直接回答您的问题,而是会引导您了解 WTF-Forms 行为。您是否尝试过发送 POST 请求而不是 GET 请求?我问的原因是因为通常保护是防止插入数据,特别是在 POST 请求中(关于 this thread 的更多信息。

此外,根据 docs,您可以将 beforeSend ajax 方法设置为以下内容:

 var csrf_token = "{{ csrf_token() }}";

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrf_token);
            }
        }
    });

## this should also technically exclude the CSRF token from the header

如果您确实尝试 POST 请求,请确保在您的路线上接受它:

@app.route("/calendar_data/", methods=('GET', 'POST'))
def calendar_data():
    if request.method == 'POST':
        print ('posted')
    stuff
return jsonify(data=data[1])

根据我的理解,如果您不将 CSRF 令牌传递给 POST 请求,或者如果它格式不正确,那么这种情况将不起作用。

GET 请求中关于 CSRF 的更多内容

根据 this cheatsheet 关于 CSRF 安全令牌:

The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. This is in fact what the RFC 2616 requires for GET requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests.

另外,根据rfc7231

Request methods are considered "safe" if their defined semantics are essentially read-only

Of the request methods defined by this specification, the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe.