1

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.

Chris
  • 18,724
  • 6
  • 46
  • 80
Ronald
  • 11
  • 2

1 Answers1

0

127.0.0.1 and localhost (or local.me.me in your case) are two different domains (and origins). Hence, when making a request you need to use the same domain you used for creating the cookie. For example, if the cookie was created for local.me.me domain, then you should use that domain when sending the request. See related posts here, as well as here and here.

You also seem to have a second FastAPI app (listenning on a different port) acting as your frontend (as you say). If that's what you are trying to do, you would need to use Session Objects in Python requests module, or preferably, use a Client instance from 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 can find more details and examples in this answer, as well as here and here.

Chris
  • 18,724
  • 6
  • 46
  • 80