pythoncookiesfastapijsonresponse

Set cookies and return the message in FastAPI


Why don't I have cookies installed in my browser when I try to return a message in this code?

@post("/registration_user")#, response_class=JSONResponse)
    async def sign_in_user(self, item: schemas.RegistrWithoutLogin):
        print("-------------------------------------------------------------------")
        self.registration_user(models.User, models.Credentials, item.middlename, item.name, item.lastname, item.phone, item.login, item.password)
        jwt_user = self.authenticate_user(item.login, item.password)
        print(jwt_user)
        print("-------------------------------------------------------------------")
        response = Response(status_code=200)
        response.set_cookie(key="Authorization", value=_T.encode_jwt(jwt_user), max_age=600)
        #role = [{"role": "user"}]
        return {"role": "user", "cookie_set": True} #JSONResponse(role, headers=response.headers)

In the code in the comments there are also options that I tried for my purpose, but they also did not install cookies in the browser.

I run everything if anything in another file Here is his code

app = FastAPI()
origins = [
    "http://localhost.GideOne.com",
    "https://localhost.GideOne.com",
    "http://localhost",
    "http://localhost:8000",

]

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

def main():
    app.include_router(AuthenticateController.create_router())
    app.include_router(Company.create_router())
    app.include_router(InviteEmployee.create_router())
    app.include_router(Criteries.create_router())
    app.include_router(OwnersDashboard.create_router())
    app.include_router(WorkersDashboard.create_router())
    app.include_router(ManagersDashboard.create_router())
    uvicorn.run(app, host="0.0.0.0", port=8000,)

if __name__ == "__main__":
    main()

Solution

  • A common mistake from inattention. It was necessary to use JSON Response instead of Response.

    @post("/registration_user")
    async def sign_in_user(self, item: schemas.RegistrWithoutLogin):
        print("-------------------------------------------------------------------")
        self.registration_user(models.User, models.Credentials, item.middlename, item.name, item.lastname, item.phone, item.login, item.password)
        jwt_user = self.authenticate_user(item.login, item.password)
        print(jwt_user)
        print("-------------------------------------------------------------------")
        role = [{"role": "user"}]
        response = JSONResponse(content=role)
        response.set_cookie(key="Authorization", value=_T.encode_jwt(jwt_user), max_age=600)
        return response