问题: 我正在尝试使用 LoginManager 来管理用户会话,但我的前端似乎没有在客户端保存 cookie。
上下文:
初始页面点击 /login 对用户进行身份验证,并使用 loging_user 设置它。然后前端触发/get_user/。但该路由受 @login_required 保护,它返回 401 错误。
我相信客户端应该使用cookie来验证用户,但我没有在浏览器上看到它。
create_app.py
app = Flask(__name__, static_url_path='',
static_folder='frontend/build/static', template_folder='frontend/build/templates')
db_uri = os.environ.get('LUNCHROULETTE_URI')
app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
db = SQLAlchemy(app)
app.py
#other imports
from create_app import app, db
# Initialize the database
db.init_app(app)
# CORS(app) # comment this on deployment
CORS(app, supports_credentials=True)
app.config['SECRET_KEY'] = '36&462134kjKDhuIS_d23'
app.config.update(
SESSION_COOKIE_SECURE=False,
SESSION_COOKIE_HTTPONLY=False,
SESSION_COOKIE_SAMESITE=None
)
# Initialize Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
email = data.get('email')
password = data.get('password')
if not email or not password:
return jsonify({'message': 'Email and password are required'}), 400
user = User.query.filter_by(email=email).first()
if not user or not user.check_password(password):
return jsonify({'message': 'Invalid email or password'}), 401
login_user(user)
print('current user: ', current_user)
print('Authen: ', current_user.is_authenticated)
return jsonify({'message': 'Login successful'})
@app.route('/get_current_user_id', methods=['GET'])
@login_required
def get_current_user_id():
response = Response(jsonify({'user_id': current_user.id}), 200)
return response, 200
⚠️ 顺便说一下,我从一个静态文件夹提供前端服务,它应该处理 CORS 策略。我的前端是 React,但我使用 npm run build 来获取静态文件。这样我就不必运行两个单独的服务器。 *我怀疑我在这里做错了
客户端
apiService.js
async function LoginUser(userData) {
//** User during Sing in */
const response = await fetch(`${API_BASE_URL}/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
credentials: "include",
},
body: JSON.stringify(userData),
});
if (!response.ok) {
throw new Error(`Error creating user: ${response.statusText}`);
}
return response.json();
}
async function getCurrentUserId() {
const response = await fetch(`${API_BASE_URL}/get_current_user_id`, {
method: "GET",
headers: {
"Content-Type": "application/json",
credentials: "include",
},
});
if (!response.ok) {
throw new Error(`Error retrieving current user ID: ${response.statusText}`);
}
return response;
}
错误:
apiService.js:40 GET http://127.0.0.1:5000/get_current_user_id 401(未授权)
在我的网络选项卡上,我看到:
请求地址: http://127.0.0.1:5000/get_current_user_id 请求方法: 得到 状态码: 401 未经授权 远程地址: 127.0.0.1:5000 推荐政策: 严格起源时交叉起源
请求标头: 接受: / 接受编码: gzip、放气、br 接受语言: en-US,en;q=0.9,es;q=0.8 联系: 活着 内容类型: 应用程序/json 证书: 包括 主持人: 127.0.0.1:5000 起源: http://localhost:5000 推荐人: http://localhost:5000/ Sec-Ch-Ua: "Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24" Sec-Ch-Ua-Mobile: ?0 Sec-Ch-Ua-平台: “苹果系统” Sec-Fetch-Dest: 空的 秒取模式: 科尔斯 Sec-Fetch-站点: 跨站 用户代理: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36