我正在尝试将 JWT 令牌存储在 Flask 应用程序的 cookie 中以限制某些端点。端点"/authorize"负责设置 Cookie,然后将页面重定向到根端点"/"。
from flask import Flask, request, make_response, redirect
@app.route("/authorize", methods=["GET"])
def authorize():
token = request.args.get('token')
expires = request.args.get('expires')
# some code to validate the token
resp_output = make_response(redirect("/"))
resp_output.set_cookie("token", token, expires=expires)
return resp_output
@app.route("/", methods=["GET"])
def index():
token = request.cookies.get("token)
# do something with the token
但是,当我尝试部署它时,我在重定向时遇到了一些问题,因此必须redirect("/")
更改为redirect("https://someaddress.com/)"
其中https://someaddress.com/
是烧瓶应用程序的地址。现在,当我尝试在根终结点中检索令牌 cookie 时,它会返回None
。我怀疑这是因为重定向已从内部重定向转向外部重定向。
请帮我找到解决方法。或者,如果您认为我应该解决导致从内部重定向更改为外部重定向的问题,以便我可以回到有效的方法。(如果有人能指出一些资源来解释重定向,或者更具体地说是 Flask 的重定向是如何工作的,我将不胜感激。
使用 flask 中的url_for
函数应该适用于您的情况,因为它将在应用程序上下文中查找链接:
from flask import Flask, request, make_response, redirect, url_for
@app.route("/authorize", methods=["GET"])
def authorize():
token = request.args.get('token')
expires = request.args.get('expires')
# some code to validate the token
resp_output = make_response(redirect(url_for('index')))
resp_output.set_cookie("token", token, expires=expires)
return resp_output
@app.route("/", methods=["GET"])
def index():
token = request.cookies.get("token)
# do something with the token
顺便说一句,我建议您将授权逻辑传递给装饰器,看看使用烧瓶的授权装饰器。
如果这在生产中不起作用,那可能是与您的反向代理相关的一些设置 - 例如 nginx conf 文件。如果是这种情况,请告诉我
在启用站点的文件夹etc/nginx/sites-enabled/<project-name>
上的 Nginx 文件上,注释或删除以下行:
proxy_set_header Host $host;
希望它适合你!