首页 > 解决方案 > AWS Flask 会话不会从 PHP 请求中持久化

问题描述

我将 Flask 应用程序部署到 AWS lambda

@bp_google_routes.route('/is_authorized', methods=('POST', ))
def google_is_authorized():
    data = json.loads(request.data)

    flask.session['user_email'] = data['email']
    authorized = aws_handler.already_authorized(data['email'])
    return jsonify({'authorized': authorized})


@bp_google_routes.route('/authorize', methods=('GET', ))
def google_authorize():
    if 'user_email' not in flask.session:
        abort(404)

    return 'All good'

我正在通过 PHP 后端访问应用程序,以首先检查is_authorized作为POST请求的授权并将其存储email在会话中。

然后在我执行第二次呼叫之后,authorize由于会话中显然没有电子邮件,该呼叫总是中止。但是应该从第一个请求开始:

<?php
    $data = array("email" => "test@test.com");                                                                  
    $data_string = json_encode($data); 
    $aws_endpoint = "https://.../is_authorized";
    $aws_endpoint_auth = "https://.../authorize";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $aws_endpoint);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json')
    );

    $response = curl_exec($ch);
    $err = curl_error($ch);

    curl_close ($ch);

    if ($err) {
        echo "There was an error accessing the requested information!";
    } else {
        $result = json_decode($response);
        if (!$result->authorized) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $aws_endpoint_auth);
            curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);

            echo $result;
            print_r('False');
        } else {
            print_r('True');
        }
    }
?>

为什么会话在两个呼叫之间不持久?

标签: phpsessionflaskaws-lambda

解决方案


您需要告诉curl使用cookiejar.

将下面的行添加到文件的顶部:

$cookieFileName = tempnam('/tmp','cookies.txt');

然后将以下curl_setopt调用添加到您的每个调用中:

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileName); 
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFileName);

这样,curl 将在请求之间存储和重用 cookie。


推荐阅读