Plug-and-Play Authentication with Keycloak in Python A developer built a plug-and-play Keycloak connector for Python that encapsulates the full OAuth 2.0/OIDC lifecycle—initialize, login, refresh, and logout—into four operations, paired with a minimal Flask demo app. The connector handles discovery metadata, JWKS signing-key caching with rotation, PKCE, state and nonce verification, RFC 9207 issuer validation, and RP-initiated logout, letting any Python web app delegate authentication to Keycloak in roughly 80 lines of integration code. Plug-and-play applications to Keycloak. Modern web applications need secure, standards-compliant authentication, yet building and maintaining identity management from scratch is both risky and time-consuming. By combining Keycloak with a lightweight, framework-agnostic Python connector, you can add enterprise-grade Single Sign-On SSO to a web application in roughly 80 lines of integration code. Keycloak https://www.keycloak.org/ is an open-source Identity and Access Management IAM solution aimed at modern applications and services. Instead of embedding login forms, password hashing, multi-factor authentication MFA , and session tracking directly inside every application you build, Keycloak centralizes these responsibilities into a dedicated identity provider. Under the hood, Keycloak implements industry-standard protocols: Keycloak organizes security boundaries into Realms . A realm manages a set of users, credentials, roles, and groups, completely isolated from other realms. Within a realm, applications are registered as Clients : While Keycloak is feature-rich, integrating OIDC flows directly into web frameworks often leads to repetitive boilerplate—handling state parameters to prevent CSRF, generating nonce values, managing PKCE code verifiers, caching JWKS signing keys, and rotating expired tokens. To solve this, we built a plug-and-play Keycloak Connector paired with a minimal Flask web application . The connector encapsulates the entire OAuth 2.0 / OIDC lifecycle into four clean operations— initialize, login, refresh, and logout —allowing any Python web application to delegate authentication to Keycloak right out of the box. The solution separates protocol mechanics from web framework routing. Your web application owns the HTTP session and browser redirects, while KeycloakConnector handles discovery, cryptography, retries, and token validation. KeycloakConfig : KEYCLOAK SERVER URL , KEYCLOAK REALM , KEYCLOAK CLIENT ID , etc. at startup so misconfigurations fail fast. KeyStore & HttpClient discovery.py : .well-known/openid-configuration , verifies the realm issuer, and caches public signing keys JWKS with automatic handling for key rotation kid . KeycloakConnector connector.py : state and nonce verification, RFC 9207 iss validation, token refreshing, and RP-initiated logout. LoginRequest & TokenSet tokens.py : At startup, the connector loads Keycloak's discovery metadata and warms its signing-key cache. When a user visits /login , login request generates cryptographic parameters state , nonce , and a PKCE code verifier and builds the authorization URL: python From connector.py def login request self, , login hint: str | None = None, prompt: str | None = None, scopes: tuple str, ... | None = None, extra params: Mapping str, str | None = None - LoginRequest: state, nonce = random token , random token verifier = generate verifier if self.config.use pkce else None params: dict str, str = { "client id": self.config.client id, "response type": "code", "redirect uri": self.config.redirect uri, "scope": " ".join scopes or self.config.scopes , "state": state, "nonce": nonce, } if verifier: params.update code challenge=challenge s256 verifier , code challenge method="S256" ... optional parameters appended ... url = f"{self. keys.endpoint 'authorization endpoint' }?{urlencode params }" return LoginRequest url=url, state=state, nonce=nonce, code verifier=verifier When Keycloak redirects back to /callback , handle callback protects against CSRF and mix-up attacks by verifying state and iss in constant time before exchanging the authorization code for tokens and validating the ID token claims: python From connector.py def handle callback self, params: Mapping str, str , login: LoginRequest | Mapping str, Any - TokenSet: if not isinstance login, LoginRequest : login = LoginRequest.from session login if params.get "error" : raise AuthorizationError params "error" , params.get "error description" received state = params.get "state" or "" if not received state or not hmac.compare digest received state, login.state : raise StateMismatchError "state of the callback does not match the login request" if params.get "iss" and params "iss" = self.config.issuer: raise StateMismatchError "issuer of the callback does not match the configured realm" code = params.get "code" if not code: raise AuthorizationError "invalid response", "callback carries neither code nor error" return self.exchange code code, login With the connector handling the OIDC protocol details, the Flask application flask app.py only needs a few concise routes and a @login required decorator that automatically refreshes expiring access tokens via kc.ensure fresh : From flask app.py kc = connector or KeycloakConnector KeycloakConfig.from env .initialize def login required view : """Redirect anonymous users to /login; refresh the access token when it is about to expire.""" @wraps view def wrapper args, kwargs : if "tokens" not in session: return redirect url for "login" try: tokens = kc.ensure fresh TokenSet.from dict session "tokens" except RefreshError: session.clear return redirect url for "login" session "tokens" = tokens.to dict return view tokens, args, kwargs return wrapper @app.get "/login" def login : request = kc.login request session "login" = request .to session return redirect request .url @app.get "/callback" def callback : pending = session.pop "login", None tokens = kc.handle callback request.args, LoginRequest.from session pending session "tokens" = tokens.to dict return redirect url for "profile" @app.get "/profile" @login required def profile tokens: TokenSet : claims = kc.validate access token tokens.access token return jsonify user=tokens.claims.get "preferred username" , roles=claims.get "realm access", {} .get "roles", , access token expires in=round tokens.expires in time.time @app.get "/logout" def logout : tokens = TokenSet.from dict session "tokens" if "tokens" in session else None session.clear return redirect kc.logout url tokens By exporting five environment variables KEYCLOAK SERVER URL , KEYCLOAK REALM , KEYCLOAK CLIENT ID , KEYCLOAK CLIENT SECRET , and KEYCLOAK REDIRECT URI , the application immediately supports full SSO login, offline JWT signature verification, automatic token refresh, and single sign-out. Everything is in place: Keycloak manages user identities, security policies, and token issuance, while the plug-and-play Python connector bridges the OAuth 2.0 / OIDC protocol directly into our web application. With discovery caching, PKCE protection, automatic token rotation, and RP-initiated logout all wired up and verified, the authentication layer is complete and ready to protect your routes. Thanks for reading 🔌