Cookie is not created when calling the endpoint in FastAPI
Asked Answered
I

1

2

I have encountered an issue, as I have to create a cookie in the backend, which I will later use to send a request from the frontend. Both apps are on the same domain. This is the general idea behind it: https://levelup.gitconnected.com/secure-frontend-authorization-67ae11953723.

Frontend - Sending GET request to Backend

@app.get('/')
async def homepage(request: Request, response_class=HTMLResponse):
    keycloak_code = 'sksdkssdk'
    data = {'code': keycloak_code}
    url_post = 'http://127.0.0.1:8002/keycloak_code'
    post_token=requests.get(url=url_post, json = data ) 
      return 'Sent'


if __name__ == '__main__':
    uvicorn.run(app, host='local.me.me', port=7999,debug=True)

Backend

@app.get("/keycloak_code")
def get_tokens(response: Response, data: dict):
    code = data['code']
    print(code)
....

    requests.get(url='http://local.me.me:8002/set') 
    return True

@app.get("/set")
async def createcookie(response: Response):
    r=response.set_cookie(key='tokic3', value='helloworld', httponly=True)
    return True


if __name__ == '__main__':
    uvicorn.run(app, host='local.me.me', port=8002, log_level="debug")

When I open the browser and access http://local.me.me:8002/set, I can see that the cookie is created. But when I make a GET request from my frontend to backend to the same URL, the request is received—as I can see in the terminal—but the backend does not create the cookie. Does anyone know what I might be doing wrong?

I have tried different implementations from FastAPI docs, but none has similar use cases.

Invert answered 11/11, 2022 at 16:59 Comment(0)
C
0

127.0.0.1 and localhost (or local.me.me in your case) are two different domains (and hence, different origins). Hence, when making a request you need to use the same domain you used for creating the cookie, in order to pass it to the backend. For example, if the cookie was created for local.me.me domain, you should then use that domain when sending the request. Please have a look at this answer, as well as this answer and this answer for more details and examples.

You also seem to have a second FastAPI application (listenning on a different port) acting as your frontend (as you noted). If that's what you are trying to do, you would need to use Session Objects in Python requests library, or preferably, use a Client instance from the httpx library, in order to persist cookies across requests. The advantage of httpx is that it offers an asynchronous API as well, using the httpx.AsyncClient(). You could find more details and examples in this answer, as well as here and here.

Christianchristiana answered 11/11, 2022 at 19:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.