{"slug": "plug-and-play-authentication-with-keycloak-in-python", "title": "Plug-and-Play Authentication with Keycloak in Python", "summary": "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.", "body_md": "Plug-and-play applications to Keycloak.\n\nModern 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.\n\n[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.\n\nUnder the hood, Keycloak implements industry-standard protocols:\n\nKeycloak 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**:\n\nWhile 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.\n\nTo 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.\n\nThe 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.\n\n`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`):\nAt 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:\n\n``` python\n# From connector.py\ndef login_request(self, *, login_hint: str | None = None, prompt: str | None = None,\n                  scopes: tuple[str, ...] | None = None, extra_params: Mapping[str, str] | None = None\n                  ) -> LoginRequest:\n    state, nonce = random_token(), random_token()\n    verifier = generate_verifier() if self.config.use_pkce else None\n    params: dict[str, str] = {\n        \"client_id\": self.config.client_id,\n        \"response_type\": \"code\",\n        \"redirect_uri\": self.config.redirect_uri,\n        \"scope\": \" \".join(scopes or self.config.scopes),\n        \"state\": state,\n        \"nonce\": nonce,\n    }\n    if verifier:\n        params.update(code_challenge=challenge_s256(verifier), code_challenge_method=\"S256\")\n    # ... optional parameters appended ...\n    url = f\"{self._keys.endpoint('authorization_endpoint')}?{urlencode(params)}\"\n    return LoginRequest(url=url, state=state, nonce=nonce, code_verifier=verifier)\n```\n\nWhen 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:\n\n``` python\n# From connector.py\ndef handle_callback(self, params: Mapping[str, str], login: LoginRequest | Mapping[str, Any]) -> TokenSet:\n    if not isinstance(login, LoginRequest):\n        login = LoginRequest.from_session(login)\n    if params.get(\"error\"):\n        raise AuthorizationError(params[\"error\"], params.get(\"error_description\"))\n    received_state = params.get(\"state\") or \"\"\n    if not received_state or not hmac.compare_digest(received_state, login.state):\n        raise StateMismatchError(\"state of the callback does not match the login request\")\n    if params.get(\"iss\") and params[\"iss\"] != self.config.issuer:\n        raise StateMismatchError(\"issuer of the callback does not match the configured realm\")\n    code = params.get(\"code\")\n    if not code:\n        raise AuthorizationError(\"invalid_response\", \"callback carries neither code nor error\")\n    return self.exchange_code(code, login)\n```\n\nWith 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()`:\n\n```\n# From flask_app.py\nkc = connector or KeycloakConnector(KeycloakConfig.from_env()).initialize()\n\ndef login_required(view):\n    \"\"\"Redirect anonymous users to /login; refresh the access token when it is about to expire.\"\"\"\n    @wraps(view)\n    def wrapper(*args, **kwargs):\n        if \"tokens\" not in session:\n            return redirect(url_for(\"login\"))\n        try:\n            tokens = kc.ensure_fresh(TokenSet.from_dict(session[\"tokens\"]))\n        except RefreshError:\n            session.clear()\n            return redirect(url_for(\"login\"))\n        session[\"tokens\"] = tokens.to_dict()\n        return view(tokens, *args, **kwargs)\n    return wrapper\n\n@app.get(\"/login\")\ndef login():\n    request_ = kc.login_request()\n    session[\"login\"] = request_.to_session()\n    return redirect(request_.url)\n\n@app.get(\"/callback\")\ndef callback():\n    pending = session.pop(\"login\", None)\n    tokens = kc.handle_callback(request.args, LoginRequest.from_session(pending))\n    session[\"tokens\"] = tokens.to_dict()\n    return redirect(url_for(\"profile\"))\n\n@app.get(\"/profile\")\n@login_required\ndef profile(tokens: TokenSet):\n    claims = kc.validate_access_token(tokens.access_token)\n    return jsonify(\n        user=tokens.claims.get(\"preferred_username\"),\n        roles=claims.get(\"realm_access\", {}).get(\"roles\", []),\n        access_token_expires_in=round(tokens.expires_in(time.time()))\n    )\n\n@app.get(\"/logout\")\ndef logout():\n    tokens = TokenSet.from_dict(session[\"tokens\"]) if \"tokens\" in session else None\n    session.clear()\n    return redirect(kc.logout_url(tokens))\n```\n\nBy 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.\n\nEverything 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.\n\n**Thanks for reading 🔌**", "url": "https://wpnews.pro/news/plug-and-play-authentication-with-keycloak-in-python", "canonical_source": "https://dev.to/aairom/plug-and-play-authentication-with-keycloak-in-python-199p", "published_at": "2026-11-20 11:10:38+00:00", "updated_at": "2026-11-20 11:14:13.844824+00:00", "lang": "en", "topics": ["developer-tools"], "entities": ["Keycloak", "Flask", "Python"], "also_reported_by": [], "takeaway": "Wrapping the OIDC lifecycle in a connector that owns discovery, JWKS caching with kid rotation, PKCE, state/nonce checks and RFC 9207 issuer validation lets a Python web app add Keycloak SSO in about 80 lines while the app keeps only session and redirect handling.", "recommendation": {"advice": "Delegate auth to a connector that verifies state, nonce and issuer in constant time and caches JWKS with kid rotation, rather than hand-rolling OIDC flows in each app.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/plug-and-play-authentication-with-keycloak-in-python", "markdown": "https://wpnews.pro/news/plug-and-play-authentication-with-keycloak-in-python.md", "text": "https://wpnews.pro/news/plug-and-play-authentication-with-keycloak-in-python.txt", "jsonld": "https://wpnews.pro/news/plug-and-play-authentication-with-keycloak-in-python.jsonld"}}