php - 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');
}
}
?>
为什么会话在两个呼叫之间不持久?
解决方案
您需要告诉curl
使用cookiejar
.
将下面的行添加到文件的顶部:
$cookieFileName = tempnam('/tmp','cookies.txt');
然后将以下curl_setopt
调用添加到您的每个调用中:
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileName);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFileName);
这样,curl 将在请求之间存储和重用 cookie。
推荐阅读
- java - java Spring @EnableResourceServer 和 @EnableWebSecurity
- python - 特定网页的 Scrapy shell
- c# - C# Accord.NET 元素加法过时了吗?
- c# - XAML 原语中的绑定
- tensorflow - 在同一个端口上加载两个不同的文件夹
- c# - 如何使用 Combobox 加载列表框
- rest - 当正文中的 ID 与路径中的 ID 不匹配时,正确的 HTTP 状态代码?
- python - Python 3.6 将 tkinter 转换为 exe 后 - SSH 功能停止工作
- vba - 需要帮助将宏从多个工作簿中的绘图信息更改为行而不是列
- python-3.x - 如何模拟 Python 类的对象?