{"id":1681,"library":"python-keycloak","title":"Python Keycloak Client","description":"python-keycloak is a Python package providing access to the Keycloak API, acting as a client for OpenID Connect and OAuth2 workflows. It is currently at version 7.1.1 and receives regular updates, typically aligning with Keycloak's own release cycles for compatibility and feature support.","status":"active","version":"7.1.1","language":"en","source_language":"en","source_url":"https://github.com/marcospereira/python-keycloak","tags":["keycloak","openid","oauth2","authentication","sso","iam"],"install":[{"cmd":"pip install python-keycloak","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"HTTP client for API interactions.","package":"requests"},{"reason":"JSON Web Token (JWT) handling, including cryptographic operations.","package":"pyjwt[crypto]"},{"reason":"Provides various utilities for the requests library, such as multipart/form-data encoding.","package":"requests-toolbelt"}],"imports":[{"symbol":"KeycloakOpenID","correct":"from keycloak import KeycloakOpenID"},{"symbol":"KeycloakAdmin","correct":"from keycloak.admin import KeycloakAdmin"}],"quickstart":{"code":"import os\nfrom keycloak import KeycloakOpenID\n\n# Configuration from environment variables or sensible defaults\nKEYCLOAK_SERVER_URL = os.environ.get('KEYCLOAK_SERVER_URL', 'http://localhost:8080/')\nKEYCLOAK_REALM_NAME = os.environ.get('KEYCLOAK_REALM_NAME', 'myrealm')\nKEYCLOAK_CLIENT_ID = os.environ.get('KEYCLOAK_CLIENT_ID', 'my-client-id')\nKEYCLOAK_CLIENT_SECRET = os.environ.get('KEYCLOAK_CLIENT_SECRET', '') # Required for confidential clients\nKEYCLOAK_USERNAME = os.environ.get('KEYCLOAK_USERNAME', 'testuser')\nKEYCLOAK_PASSWORD = os.environ.get('KEYCLOAK_PASSWORD', 'password')\n\n# Initialize KeycloakOpenID client\nkeycloak_openid = KeycloakOpenID(\n    server_url=KEYCLOAK_SERVER_URL,\n    realm_name=KEYCLOAK_REALM_NAME,\n    client_id=KEYCLOAK_CLIENT_ID,\n    client_secret_key=KEYCLOAK_CLIENT_SECRET, # Pass if client is confidential, otherwise omit\n    verify_ssl_cert=False # Set to True for production, False for dev/self-signed certs\n)\n\ntry:\n    # Get initial tokens using Direct Access Grant (Resource Owner Password Credentials Flow)\n    # Note: This flow is generally not recommended for public clients (e.g., browser-based apps)\n    # and should be used cautiously, primarily for trusted backend services or CLI tools.\n    token = keycloak_openid.token(KEYCLOAK_USERNAME, KEYCLOAK_PASSWORD)\n    print(\"Successfully obtained token:\")\n    print(f\"  Access Token (first 10 chars): {token.get('access_token', '')[:10]}...\")\n    print(f\"  Refresh Token (first 10 chars): {token.get('refresh_token', '')[:10]}...\")\n    print(f\"  Expires in: {token.get('expires_in')}s\")\n\n    # Example: Verify token\n    decoded_token = keycloak_openid.decode_token(token['access_token'])\n    print(f\"  Decoded Access Token Subject: {decoded_token.get('sub')}\")\n\n    # Example: Refresh token\n    if 'refresh_token' in token and token['refresh_token']:\n        print(\"\\nAttempting to refresh token...\")\n        refreshed_token = keycloak_openid.refresh_token(token['refresh_token'])\n        print(\"Successfully refreshed token:\")\n        print(f\"  New Access Token (first 10 chars): {refreshed_token.get('access_token', '')[:10]}...\")\n        print(f\"  New Expires in: {refreshed_token.get('expires_in')}s\")\n    else:\n        print(\"No refresh token available or provided.\")\n\nexcept Exception as e:\n    print(f\"Error during Keycloak interaction: {e}\")\n    print(\"Please ensure Keycloak is running, the realm, client ID/secret, and user credentials are correct.\")\n    print(\"Also, verify 'Direct Access Grants' is enabled for the client in Keycloak's client settings.\")","lang":"python","description":"Demonstrates how to initialize the `KeycloakOpenID` client, obtain an access token using the Direct Access Grant (Resource Owner Password Credentials) flow, decode the token, and refresh it. Remember to configure your Keycloak server with a realm, client, and user. Set `verify_ssl_cert=True` in production environments."},"warnings":[{"fix":"Review the official documentation for `KeycloakAdmin` initialization in version 7.x. Update your `KeycloakAdmin` constructor calls to provide all necessary direct configuration parameters instead of passing a `KeycloakOpenID` instance.","message":"The `KeycloakAdmin` client's constructor significantly changed between versions 6.x and 7.x. Previously, it could accept a `KeycloakOpenID` object; now, it requires direct configuration parameters such as `server_url`, `realm_name`, `username`, `password`, `client_id`, and `client_secret_key`.","severity":"breaking","affected_versions":"7.0.0 and above"},{"fix":"For development or testing with self-signed certificates, explicitly set `verify_ssl_cert=False` in the `KeycloakOpenID` or `KeycloakAdmin` constructor. Always re-enable `verify_ssl_cert=True` for production deployments.","message":"SSL certificate verification is enabled by default (`verify_ssl_cert=True`). This will cause connection errors with self-signed certificates or development setups that don't use valid CA-signed certificates.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure `client_secret_key` is passed to `KeycloakOpenID` or `KeycloakAdmin` constructors ONLY if your Keycloak client is configured as 'confidential'. For public clients, ensure this parameter is omitted or set to `None`.","message":"Confusing 'client_secret_key' parameter behavior for confidential clients. If your Keycloak client is confidential, you MUST provide `client_secret_key` during initialization. Public clients (e.g., SPA, mobile apps) should omit this parameter, and its presence can lead to authentication failures.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}