Setting up Keycloak for SSO

I saw https://www.datamate.org/installation-keycloak-sso-ubuntu-18-04/ which gave me some insights as to where to start with getting Seafile set up with Keycloak, but it seems things have changed enough that it’s no longer working quite the same way. So, after figuring out what else I needed, I figured I’d write something up in case somebody else wants to do this.

This is using Keycloak 26.0.0 and Seafile CE server 11.0.12. It also assumes you have a working Keycloak installation already.

To start with, you’ll need to set up an OpenID client in Keycloak. You can use settings like these for it (though adding additional randomness to the client ID can increase the effective complexity of the secret).

That should give you a client that looks something like this:

You should also have a credentials tab (which is made available by turning on client authentication):

The client secret will be used in the Seahub configuration, so you’ll want to click the copy button to get a copy of it and paste it somewhere temporarily.

From there, you just need to note the realm you use and your Keycloak server’s hostname, and you can start making changes on the Seafile side. Those changes are made in seahub_settings.py. Specifically, they’re:

ENABLE_OAUTH = True
OAUTH_CREATE_UNKNOWN_USER = True
OAUTH_ACTIVATE_USER_AFTER_CREATION = True
OAUTH_CLIENT_ID = "client_id"
OAUTH_CLIENT_SECRET = "client_secret"
OAUTH_REDIRECT_URL = "https://seafile.example.com/oauth/callback/"

OAUTH_PROVIDER_DOMAIN = 'seafile.example.com'
OAUTH_AUTHORIZATION_URL = 'https://keycloakinstance.com/realms/KeycloakRealm/protocol/openid-connect/auth'
OAUTH_TOKEN_URL = 'https://keycloakinstance.com/realms/KeycloakRealm/protocol/openid-connect/token'
OAUTH_USER_INFO_URL = 'https://keycloakinstance.com/realms/KeycloakRealm/protocol/openid-connect/userinfo'
OAUTH_SCOPE = ["openid", "profile", "email"]
OAUTH_ATTRIBUTE_MAP = {
    "sub": (True, "uid"),
    "email": (False, "contact_email"),
    "name": (False, "name")
}

The real magic there is OAUTH_SCOPE and OAUTH_ATTRIBUTE_MAP. The scope requests an OpenID token with profile and email data (as defined in the OpenID specification), and the attribute map maps values returned by Keycloak to specific key fields within Seafile. In particular, it maps the sub field, which is a unique user identifier on the Keycloak side, to the uid field in Seafile, maps the email field in Keycloak to contact_email in Seafile (since the user’s e-mail address will be generated as an internal one in Seafile; having a contact e-mail address set allows the user to have something actually usable), and name in Keycloak to name in Seafile. It also declares that the uid field in the token is mandatory (the True part), and the other fields are optional (the False parts).

Finally, it allows users to be created and activated if they successfully authenticate against the Keycloak instance.

2 Likes