1

我正在创建一个简单的身份验证系统并在以下位置有一个简单的游戏项目:https ://github.com/ericg-vue-questions/authentication

我使用的主要技术是:

  1. 后端服务器的FastAPI
  2. 用于前端 UI 的Vue
  3. axios 从前端到后端的通信(最终,一个标准的 OpenAPI 客户端)

我通过以下方式拨打 axios电话

axios
  .get('http://127.0.0.1:8000/api/login', {
    params: {
      username: username,
      password: password
    },
    withCredentials: true
  })
  .then((response) => {
    console.log('Logged in')
    console.log(response)
  })
  .catch(err => { console.log(err) })

在后端,设置 cookie 的代码是:

@app.get("/api/login", tags=["api"], operation_id = "login" )
async def login( username: str, password: str, response: Response ):

    authenticated = False

    if username in users:
        if users[ username ][ 'password' ] == password:
            authenticated = True
            response.set_cookie( key="user", value=str( users[ username ][ 'id' ] ), max_age = 60 * 60 * 24 )

    return authenticated

我可以确认 cookie 正在浏览器中发送和接收,但由于某种原因它没有被存储。我认为唯一需要的是在 axios 获取请求中设置 withCredentials: true ,但这似乎不起作用。知道我可能做错了什么吗?

我的响应标头是:

HTTP/1.1 200 OK
date: Sun, 15 Dec 2019 01:54:14 GMT
server: uvicorn
content-length: 4
content-type: application/json
set-cookie: user=userid; Max-Age=86400; Path=/
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:8080
vary: Origin
4

1 回答 1

0

我很确定这是因为您没有为您的 cookie 设置路径,例如“/”。这是 set 中的第四个参数。如果您在 https 连接中使用 cookie,您还应该设置一个域。

于 2019-12-13T18:10:27.133 回答