I'm developing a web-server based on FastAPI, to be integrated into a container to be deployed on Kubernetes with replicas. Authentification is performed by authlib and Keycloak. The server which redirects (via the /login) the user to the identity provider may not be the same as the one which runs the /auth route. I may be able to build the redirection URL using the IP address of the server running the /login request, but this does not sound right for me, especially for the keycloak allowed redirect URLs which would be static IPs. Here is a code snippet I wrote: oauth = OAuth() oauth.register( name="keycloak", client_id=settings.keycloak.client_id, client_secret=settings.keycloak.client_secret.get_secret_value(), server_metadata_url=settings.keycloak.server_metadata_url, # The group scope does not exist by default. This must be added. client_kwargs={"scope": "openid email profile group"}, # The state is a value which is used as a kind of CSRF check. # When the /login redirects to keycloak, it includes this value. # Later, when keycloak redirects to /auth, it also includes the state value. # If the values mismatche, a CSRF error is raised. # Configuring it is required to perform replication. state="toto", ) oauth_client: StarletteOAuth2App = oauth.keycloak def get_user_name(userinfo: dict): """Get the user name from user information dict.""" return userinfo.get("name", None) or userinfo.get("preferred_username") @router.get("/login", tags=["user"]) async def login(request: Request): """Redirect the user to keycloak login page.""" redirect_uri = request.url_for("auth") return await oauth_client.authorize_redirect(request, redirect_uri, state="toto") @router.get("/auth", tags=["user"]) async def auth(request: Request): """Authentificate the user by creating a session cookie.""" token = await oauth_client.authorize_access_token(request) userinfo = token["userinfo"] # Needs json.dumps otherwise this is not correctly saved in session request.session["user"] = json.dumps(userinfo) _LOGGER.info("User %s got connected", get_user_name(userinfo)) # Get the URL the user requested before login, if any. target_url = request.session.pop("target-url", "/") return RedirectResponse(target_url) I wrote a small comment to explain what I understood about the state value. The key question may be the state parameter value which should be the same across servers. Yet, the documentation is not clear on how to use it. Besides, this answer indicates the value should be random to prevent attacks. So, How could I do that? Continue reading...