Usage
To set up SSO with Keycloak in your nameko service, follow these steps.
Get Keycloak configuration from realm -> Clients -> Installation, download as Keycloak OIDC JSON.
Note
Make sure
auth-server-url
ends with a trailing slash.Save this configuration in a .json file.
Add the mixin and dependency provider to your service and point to OIDC JSON config:
from nameko_keycloak.dependencies import KeycloakProvider from nameko_keycloak.service import KeycloakSsoServiceMixin class MyService(KeycloakSsoServiceMixin): keycloak = KeycloakProvider("/tmp/keycloak.json")
Set up URLs for HTTP endpoints. The mixin exposes five methods prefixed with
keycloak_
, which you should use in your HTTP service. Delegate from your entrypoints like this:@http("GET", "/login") def login_sso(self, request): return self.keycloak_login_sso(request)
This way it is up to you to control the URL routes and any middleware or extra request handling (such as CORS headers).
Implement a
fetch_user()
method on your service that takes user’s email address as a single argument and returns a user instance for that email (orNone
if no such user exists in whatever storage you’re using).Note
We assume that email address is unique for every user.
For example:
def fetch_user(self, email: str) -> Optional[User]: user_manager = UserManager(self.db.session) return user_manager.get_by_email(email)
This method is used to ensure that there is a local application user who matches the global identity stored in Keycloak.
(Optionally) Implement success and failure hook methods on your service.
If you provide
keycloak_success()
method, the mixin will call it after successful login and redirect from Keycloak back to your application. The method will receive currently logged user as its argument. Similarly the mixin will callkeycloak_failure()
upon Keycloak errors.Example:
def keycloak_success(self, user: User) -> None: logger.info(f"Successful login: {user=}") def keycloak_failure(self) -> None: logger.error("Failed to log in")
Note
Failure hooks execute in a try/except block, so you can access
sys.exc_info
, for example to capture exception to Sentry or other error reporting tool.