Home > database >  The browser cannot receive cookies using FastAPI's set_cookie method
The browser cannot receive cookies using FastAPI's set_cookie method

Time:01-12

Currently, I am using a backend with FastAPI (port 8000) and a frontend with Solid-JS (port 3000).

I want to send a refresh token from the backend server to the client when they log in.

For login, I send a request from the client using Axios like below:

const onClickLogin = () => {
    axios({
      method: 'post',
      url: 'http://localhost:8000/login',
      responseType: 'json',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: {
        username: inputUsername(),
        password: inputPw(),
      },
    }).then((response) => {
      props.setToken(response.data.access_token);
      props.updateUserinfo();
      props.setPageStatus('loggedin');
    });
  };

When the FastAPI server receives the request, it sends an access token through content and I want to send a refresh token through httponly cookie for security like below.

@app.post('/login', summary='Create access and refresh tokens for user', response_model=TokenSchema)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    ...

    response = JSONResponse({'access_token': create_access_token(user['id'])})
    response.set_cookie(key='refresh_token_test', value=create_refresh_token(user['id']),
                        max_age=REFRESH_TOKEN_EXPIRE_MINUTES, httponly=False, samesite='none', domain='http://localhost:3000')

    return response

In this case, I just disabled the 'httponly' option to check the cookie more easily in Chrome developer tools.

It is very difficult to check what is the problem because the response is received successfully and does not return any error or warnings but there are just no cookies.

I also set the CORS setting in FastAPI like below.

origins = [
    'http://localhost:3000'
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Is there any reasons that the browser does not receive cookies? Is there any method to debug this case?

CodePudding user response:

I solved the issue by changing the domain parameter from 'http://localhost:3000' to just 'localhost', as well as changing the samesite parameter to 'lax'.

  • Related