我使用Flask和flask-jwt-extended在我的服务器上进行身份验证。当我使用Postman时,我所有的cookie都设置正确。但是,当我使用浏览器和原生react时,没有存储任何cookie。
Environment:
Flask Backend: 127.0.0.1:5000
React-Native Front: 127.0.0.1:19006这是我的Flask配置:
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", 'local-secret')
JWT_TOKEN_LOCATION = ['cookies']
JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(seconds=1800)
JWT_COOKIE_SECURE = False
CORS_HEADERS = "Content-Type"
JWT_REFRESH_TOKEN_EXPIRES = datetime.timedelta(days=15)
JWT_COOKIE_CSRF_PROTECT = True # set_refresh_cookies() will now also set the non-httponly CSRF cookies
JWT_CSRF_CHECK_FORM = True
JWT_ACCESS_CSRF_HEADER_NAME = "X-CSRF-TOKEN-ACCESS"
JWT_REFRESH_CSRF_HEADER_NAME = "X-CSRF-TOKEN-REFRESH"
SSL_REDIRECT = Falsejwt = JWTManager()
app = Flask(__name__)
app.config.from_object(APP_CONFIG[CONFIG_ENV])
cors = CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:19006"}}, supports_credentials=True)
APP_CONFIG[CONFIG_ENV].init_app(app)
jwt.init_app(app)下面是我如何存储cookie(经典的,和邮递员一起工作):
access_token = create_access_token(identity = token_identity)
refresh_token = create_refresh_token(identity = token_identity)
resp = jsonify({"access_token": access_token, "refresh_token": refresh_token})
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)但是,每当我使用浏览器(127.0.0.1:19006)和原生反应进行请求时,cookie永远不会被存储。
你知道问题出在哪里吗?
发布于 2020-08-17 07:32:00
经过几个小时的努力,解决方案比我想象的要简单:在前面的代码(react-native)中,我必须添加:
credentials: "include"在我的fetch请求中。
请参阅:https://developers.google.com/web/updates/2015/03/introduction-to-fetch
发布于 2020-08-17 02:35:08
您可能会遇到一种称为同源策略的web浏览器安全机制,它会处理这两个urls和两个不同的域,因此不会保存cookies。您可以使用一个webpack代理/apache/nginx来为来自同一个域的应用程序接口和前端提供服务,或者可能查看CORS设置以允许此设置工作。
发布于 2021-09-20 15:02:23
我也有这个问题。这是我所做的:
包含前端:添加凭证:“”执行fetch请求时:
fetch(domain + "/createAccount", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify(inputData),
})
.....后端:确保将Access-Control-Allow-Origin设置为url http://localhost:3000,将Access-Control-Allow-Credentials设置为True,将samesite设置为None,将secure设置为True。
resp = Response(
.......
)
resp.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
resp.headers.add('Access-Control-Allow-Credentials', 'true')
resp.set_cookie('token', value=encoded_jwt, httponly= True, expires = TOKEN_EXPIRY_DATE, samesite='None', secure=True)https://stackoverflow.com/questions/63437422
复制相似问题