【发布时间】:2020-07-28 20:44:38
【问题描述】:
我有以下问题。我正在尝试设置 httpOnly cookie,但没有任何反应。我花了几个小时试图解决这个问题,但我不知道发生了什么......我的架构如下:
后端:Heroku 上托管的 Python fast-api,地址为 https://api.mysuperdomain.com。
前端:GatsbyJs 托管在 Netlify 上,地址为 https://mysuperdomain.com
当我从 React 组件调用登录请求时:
const handleSubmit = async (e) => {
e.preventDefault()
const config = {
headers: {
crossDomain: true,
withCredentials: true,
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const requestBody = {
username: emailRef.current.value,
password: passwordRef.current.value
}
try {
const data = await axios.post('https://api.mysuperdomain.com/login', qs.stringify(requestBody), config)
我从后端收到带有标头 set-cookie 的响应:
set-cookie: Authorization="Bearer somethinghere"; Domain=.mysuperdomain.com; expires=Tue, 28 Jul 2020 20:40:32 GMT; Max-Age=1800; Path=/; SameSite=lax
很遗憾,在浏览器存储中我看不到这个 cookie。
我的后端(API)通过以下方式设置 cookie:
@app.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": form_data.username}, expires_delta=access_token_expires
)
token = jsonable_encoder(access_token)
response = JSONResponse({'status': 'authenticated'})
response.set_cookie(
key="Authorization",
value=f"Bearer {token}",
domain=".mysuperdomain.com",
httponly=True,
max_age=1800,
expires=1800,
)
return response
我的 DNS 记录在 Cloudflare 中,后端的 CNAME 记录被代理:
Typ Name Content TTL Proxy status
CNAME api limitless-starfish-something.herokudns.com Auto Proxied
SSL/TLS 加密模式是灵活的(加密浏览器和 Cloudflare 之间的流量)。 Heroku 的后端没有 SSL 证书,因此我设置了灵活的 SSL/TLS 加密模式。
也许它与上面的配置有某种关系?
【问题讨论】:
标签: reactjs heroku netlify setcookie fastapi