Matrix and Keycloak SSO integration

Connect a self-hosted Matrix homeserver to Keycloak using either Synapse's built-in OpenID Connect support or Matrix Authentication Service, with back-channel logout planned from the start.

On this page

Matrix and Keycloak SSO integration: which route fits your homeserver

Your Matrix server must sign users in through an existing Keycloak realm, and you have two supported routes: Synapse's own oidc_providers setting, which points the homeserver directly at Keycloak, or Matrix Authentication Service (MAS), which uses Keycloak as an upstream OpenID Connect provider while MAS handles Matrix sessions and tokens. The choice decides where login, token issuance and logout are handled, so it should be made before any Keycloak client is created. Keycloak supports OpenID Connect, so either route works with the same realm, but the client settings, redirect URIs and session lifetimes differ between them.

With direct oidc_providers configuration, Synapse itself exchanges the authorization code with Keycloak and manages Matrix access tokens. With MAS, Keycloak authenticates the person, MAS issues the Matrix session, and Synapse trusts MAS. Ask your identity team which Keycloak realm and clients will serve Matrix, who administers them, and whether any other application already shares the same realm and session policies. Confirm the exact Synapse version you run, because Synapse v1.157.0 removed the deprecated experimental MSC3861 auth delegation in favour of the stable MAS integration, which affects any server still on that older pattern.

Back-channel logout is the feature that makes logout from Keycloak reach Matrix. Keycloak can notify the relying party server to end its session, and Synapse supports this when backchannel_logout_enabled is set and Keycloak is given a back-channel logout URL. The Keycloak documentation covers the Keycloak side of the setup, and the Synapse OpenID guide covers the homeserver side, so both teams need the same configuration plan. Confirm with your security team whether Matrix sessions must end within a set window after a Keycloak logout, and test that behavior on a staging realm before you rely on it for offboarding.

What you need in place before Keycloak sign-in works

Keycloak sign-in for Matrix depends on a few decisions made before any configuration: the Synapse release and its platform floor, the Keycloak release and database, the server name that users and rooms will carry, and the network paths between Synapse, MAS and Keycloak. Settle these first, because changing the server name or database later is far more disruptive than choosing it correctly now.

Synapse version and platform floor

Synapse 1.143.0 and later require PostgreSQL 14 or newer, and 1.142.0 and later require Python 3.10 or newer. The current release listed on the Synapse GitHub releases page is v1.163.0, but confirm the version you deploy against your own upgrade plan, reading the notes for every release in between. Check that your PostgreSQL and Python hosts meet these floors before you start, because Synapse drops support for versions that reach upstream end of life.

Synapse upgrade notes

Keycloak release line

Keycloak 26.8.1 is the current release listed, published October 13, 2026. Since Keycloak 26.0, minor releases arrive four times a year and breaking changes in minor releases are opt-in, so pin a release line and schedule upgrades deliberately. Red Hat build of Keycloak is a separate supported distribution with its own version numbering, so confirm which build your organization is licensed to run before you choose the artifact.

Keycloak upgrading guide

Supported production database

Keycloak supports MariaDB, Microsoft SQL Server, MySQL, Oracle Database, PostgreSQL (14 to 18), EnterpriseDB Advanced, Amazon Aurora PostgreSQL and Azure SQL in production. The default dev-file database is for development only. Choose a database your team can back up, restore and patch, and confirm it is on Keycloak's supported list for the release you select. Keycloak's high availability designs also require a synchronously replicated database.

Keycloak database guide

server_name and DNS decisions

The server_name setting fixes how user IDs such as @user:example.com and room identifiers are issued, and it cannot be casually changed once users exist. Decide it before the first login, then plan DNS for the homeserver host and any delegation so clients reach the right server on port 443. Keep Keycloak and MAS hostnames separate from the Matrix domain, and record the redirect URIs each service will use so that they match exactly during registration.

TLS certificates for each service

Synapse, MAS and Keycloak each serve HTTPS, and the browser, the Matrix clients and the back-channel calls all have to trust those certificates. Issue certificates for every hostname in the flow, and make sure the internal CA, if you use one, is trusted by the Synapse and MAS hosts. Certificate expiry on the Keycloak issuer is a common cause of sudden sign-in failures, so record renewal ownership before go-live.

Reachability between Synapse, MAS and Keycloak

Synapse or MAS must reach the Keycloak discovery document and token endpoint over the network, while the user's browser must reach Keycloak for the login redirect. Map each direction through firewalls, reverse proxies and any split DNS, and confirm that the issuer URL in the configuration matches what Keycloak advertises. Plan the connection path for back-channel logout as well, because Keycloak must call a URL on your Matrix side.

Synapse OIDC or Matrix Authentication Service: how to choose

Synapse can accept OpenID Connect logins directly. You add an entry under oidc_providers in the homeserver configuration, give it an idp_id such as keycloak, and point it at your Keycloak realm. Synapse runs the login flow, validates the identity it receives from Keycloak, and creates or matches the Matrix account itself. Matrix client sessions stay inside Synapse, so the homeserver remains the service that issues access tokens. This keeps the number of moving parts low, which suits a deployment that already runs Synapse and wants SSO added without a new service. The Synapse OpenID guide includes a Keycloak example for this entry.

  • Configuration footprint: one homeserver configuration change and one Keycloak client, with no additional service to run.
  • Session ownership: Synapse issues and revokes Matrix sessions, while Keycloak controls the upstream login.
  • Back-channel logout: Synapse supports it through backchannel_logout_enabled, and Keycloak needs a back-channel logout URL, so a logout in Keycloak ends Synapse sessions.
  • Other login sources: Synapse also offers saml2_config and CAS, so one homeserver can accept more than one login source.
  • Experimental delegation: confirm that your configuration uses oidc_providers and not the experimental MSC3861 delegation, which is covered in a separate tab.

Before testing a login, check the redirect URI in the Keycloak client and the idp_id against the Synapse guide.

Configuring Keycloak and Synapse for OIDC sign-in, step by step

This sequence connects a Keycloak realm to a self-hosted Synapse homeserver through an oidc_providers entry, then enables back-channel logout so a Keycloak logout also ends the Matrix session. Each step ends with a check you can run before moving on.

  1. Confirm versions and documented settings

    Before changing anything, record the Synapse and Keycloak versions you run and open the current Synapse OpenID Connect guide and the Keycloak section of the same documentation. Client settings, claim names and config keys can change between releases, so the reader should confirm each value in this sequence against those pages for their exact versions. Done means you have a written list of the versions and the config keys you will use, checked against the documentation for those versions.

  2. Create the Keycloak realm and Synapse client

    In the Keycloak admin console, create or select a realm for Matrix users, then create an OpenID Connect client for Synapse. Set the client to confidential, record the client secret in your secrets store, and set the valid redirect URI to the callback path Synapse expects under your public homeserver base URL, as shown in the Synapse OIDC guide. Done means the client exists and a test user in the realm can see the client in the account and client lists without errors.

  3. Add the oidc_providers entry in Synapse

    In homeserver.yaml, add an oidc_providers entry with idp_id set to keycloak, the Keycloak issuer URL for your realm, the client ID and the client secret loaded from your secrets store rather than typed into the file. Map the subject, display name and any email claims that Synapse needs to build the Matrix user ID, following the claim mapping in the Synapse guide. Done means Synapse starts after a configuration check and the Matrix login page lists a Keycloak option.

  4. Enable back-channel logout in Synapse

    Set backchannel_logout_enabled to true on the keycloak entry in oidc_providers, using the key name shown in the Synapse Keycloak documentation. Restart Synapse so the setting takes effect. Done means the running configuration reflects the change and Synapse logs no errors about the OIDC provider at startup.

  5. Register the back-channel logout URL in Keycloak

    In the Keycloak client settings for Synapse, enter the back-channel logout URL that Synapse's Keycloak documentation gives for your idp_id, and confirm the client is set to send logout notifications. The URL must be reachable from Keycloak over the network path you have planned, so check that your reverse proxy and firewall rules allow it. Done means the client saves the URL without validation errors.

  6. Test a Matrix sign-in through Keycloak

    Sign in to Element or another Matrix client with a test user from the realm, choosing the Keycloak option. Check that the Matrix user ID matches what your claim mapping should produce and that the user can open a room. Done means the login completes, the user ID is correct and the session appears in Synapse's account view for that user.

  7. Verify logout propagates from Keycloak

    With the test session still open in a Matrix client, sign the same user out of Keycloak, either through the Keycloak account console or the admin console. Then check whether the Matrix session is ended without a manual action. Done means the Matrix session no longer works after the Keycloak logout. If it stays active, review the logout URL, client settings and Synapse logs before testing again.

How back-channel logout ends Matrix sessions when Keycloak signs out

Back-channel logout lets a single sign-out from Keycloak end Matrix sessions on the Synapse side, without relying on the user's browser. When a user ends their Keycloak session, Keycloak sends a logout token directly from its server to the back-channel logout URL registered for the client. Synapse receives that request when backchannel_logout_enabled is set on the matching oidc_providers entry, and it uses the token to identify the user's sessions and end them. The Keycloak side needs the back-channel logout URL configured on the Matrix client, and the Synapse side needs the idp_id and client settings to match what Keycloak has registered. Because the request is server to server, it does not depend on the user's browser still being open, which is the main reason to prefer it over front-channel logout.

The mechanism has clear limits. It covers sessions that Synapse associates with the Keycloak identity that signed out. It does not reach clients that were signed in on other devices unless their sessions are tied to that same identity and the logout is processed, and it does not clear access tokens or cached credentials that a client already holds until they expire or are refreshed. A user who signs out only in Element on one device has ended only that device's session, not the Keycloak session, so other devices stay signed in. Check the Keycloak logout settings and token lifetimes with your identity team before you describe the behavior to users or auditors.

Test the path end to end before go-live. Sign in to Element on two devices, sign out of Keycloak in a third browser, and confirm that both Matrix sessions end as expected. Then repeat the test with a Matrix-only sign-out and with a closed browser, and record which sessions survive. Check the Synapse logs for the logout request and confirm that failures are visible to your operators. Confirm the exact behavior in the Synapse Keycloak guidance and your Synapse version's notes before you write the expected results into your runbook.

Login and logout flow between Matrix, Keycloak and the client

The flow starts when a Matrix client requests sign-in and is redirected to the homeserver, either Synapse with oidc_providers or Matrix Authentication Service (MAS). The homeserver then redirects the browser to Keycloak, which returns an authorization code to the homeserver's callback endpoint. On logout, Keycloak sends a back-channel logout request to the homeserver, which must be enabled on both sides. Check that the callback and back-channel endpoints are reachable only in the directions the diagram shows.

Sign-in redirects and the back-channel logout path between the three trust zones.

How Keycloak claims map to Matrix user IDs and attributes

This table compares how each Keycloak claim feeds a Matrix localpart, display name, email or admin status under Synapse oidc_providers and under MAS upstream provider configuration. Read each row as a question to answer from your own token output, because claim names and template behavior depend on your realm, client scopes and the mapper settings you choose.

Matrix fieldTypical Keycloak sourceSynapse oidc_providersMAS upstream provider
Localpart (user ID)preferred_username or sub claim, depending on your mapperSet through localpart_template in the provider entry, using Jinja-style templating on the claimSet through the claims_imports localpart template in the upstream provider configuration
Display namename, or given_name plus family_nameSet through display_name_template in the provider entrySet through the displayname template in the upstream provider configuration
Email addressemail, with email_verified in the tokenSet through email_template, and whether the address is trusted depends on your email settingsSet through the email import in the upstream provider configuration, with verification rules set separately
Group or role membershipGroups or realm roles mapped into a token claim by a Keycloak protocol mapperNot used for access control by default; any group-based rule needs a custom approach or a module you choose and verifyCan be used in MAS policy and upstream rules, so confirm the claim is present in the ID token or userinfo response
Admin statusA group or role such as one you create for Matrix administratorsAdmin rights are granted in Synapse configuration or the database, not from the token by defaultAdmin status is managed through MAS administration settings, so confirm how your MAS version grants it
Subject identifiersub, the stable Keycloak user IDUsed to link existing identities to the upstream accountUsed as the stable upstream subject for the MAS user link

Security settings for Keycloak-backed Matrix sign-in

Signing Matrix users in through Keycloak moves the trust boundary to the identity provider, and the Synapse and Keycloak settings around that boundary decide who can reach the homeserver. The cards below cover the controls to set before go-live: secrets, access rules, password fallbacks, network exposure and administrative surfaces. Each one should be checked in your own environment and written into your change record.

Client secret handling

The OIDC client that Synapse uses to talk to Keycloak has a client secret, and anyone holding it can impersonate that client during token exchange. Store the secret in your secrets manager or a Kubernetes secret, reference it from the oidc_providers entry rather than writing it into a file that is committed to version control, and rotate it on a schedule you can audit. Confirm which client authentication method your Keycloak client uses and record who can read the secret in each environment.

Synapse OIDC guide

Restricting who can sign in

Keycloak authenticates anyone who exists in the realm, so a realm with contractors, service accounts or former staff will let them reach Matrix unless you limit it. Decide which Keycloak groups or roles map to Matrix access, enforce that in the Keycloak client or authentication flow, and check the claim mapping in Synapse so that only expected user IDs are created. Test with an account outside the permitted group before users are onboarded.

Disabling open password registration

Once SSO is live, local password registration in Synapse becomes a second way in that bypasses your identity policy and MFA. Confirm that open registration is off in the Synapse configuration, and check whether any local password login is still enabled for accounts you have not migrated. Document a break-glass path for administrators so that disabling the fallback does not lock out the people who must fix an outage.

Firewalling the federation listener

Synapse federates on port 8448 by default, and the Synapse docs recommend firewalling that listener when federation is not needed for your users. Use federation_domain_whitelist to restrict federation to listed domains, and an empty list disables it entirely. Confirm the setting against your federation policy, then test that the listener is reachable only from the networks you intend.

Synapse federation docs

Protecting the Synapse admin API

The Synapse admin API can create users, reset passwords and change room state, so it should never be exposed through the public client listener. Restrict the admin paths at the reverse proxy to an administrative network or VPN, and confirm that the admin endpoints are not reachable with an ordinary user token. Log administrative actions and review who holds admin rights after each SSO change.

Synapse configuration manual

Keeping the Keycloak admin console private

The Keycloak admin console controls realms, clients, identity brokering and user credentials, so it is a high-value target. Serve it on a hostname or network path that is not reachable from the internet, separate it from the public login endpoints that Matrix clients use, and require strong administrator authentication. Confirm your production hostname and proxy rules against the Keycloak production configuration guide before publishing the realm.

Keycloak production guide

Common Keycloak and Matrix login failures and fixes

This table pairs common Keycloak and Matrix SSO failures with their likely cause and the first check to run. Read each row as a triage path: start with the symptom your users report, then confirm the cause before changing settings. The main takeaway is that most login failures trace back to a small set of mismatches between Keycloak client settings, the Synapse or MAS configuration, and the public server name.

SymptomLikely causeFirst check
Redirect URI mismatch error at KeycloakThe valid redirect URI in the Keycloak client does not exactly match the callback URL Synapse or MAS sends, often because of a host, port or path differenceCompare the callback URL in the server logs with the valid redirect URIs on the Keycloak client, character by character
Discovery or issuer errors at startupThe issuer or discovery URL in the oidc_providers entry or MAS upstream provider points at the wrong realm, or the issuer does not match the URL Keycloak advertisesOpen the realm's OpenID configuration URL in a browser from the homeserver host and compare its issuer value with the configured one
Users cannot log in after an account mapping changeThe localpart or display name mapping now produces a different Matrix user ID than the one already stored for that personCheck which Matrix user ID the identity provider subject now maps to and compare it with the existing account in the database
SSO login creates a second accountThe external identity is not linked to the existing Synapse user, usually because the subject mapping or the localpart changed, so Synapse creates a new userLook up the existing user ID and confirm the mapping rule produces the same localpart before enabling SSO for those users
Back-channel logout does not reach SynapseKeycloak cannot reach the Synapse back-channel logout endpoint because of network rules, a TLS certificate problem, or backchannel_logout_enabled is not setConfirm backchannel_logout_enabled is set in Synapse, then test the logout URL from the Keycloak host with curl and check the TLS chain
Logout in Keycloak does not end the Matrix sessionThe back-channel logout URL is missing or points at an old hostname, so the notification never arrivesCheck the back-channel logout URL on the Keycloak client against the public Synapse address and review Keycloak event logs for failed sends
Login loop or unexpected error after MAS upgradeStale configuration from the experimental MSC3861 delegation remains, or the MAS upstream entry does not match the Synapse setup it replacesReview the upgrade notes for the Synapse version in use and confirm that the homeserver no longer carries MSC3861 delegation settings
Login works for some users but not othersKeycloak realm roles, required actions or a disabled account block certain users, or the claim the mapping expects is missingInspect the ID token claims for a failing user and compare them with the claims the mapping template reads

What changes when you move from Synapse OIDC to MAS

Moving from Synapse OIDC to Matrix Authentication Service (MAS) changes who owns the login. With Synapse's own oidc_providers block, Synapse redirects users to Keycloak and then issues Matrix sessions itself. With MAS, MAS takes over authentication and token issuance, and Synapse delegates login to it. Synapse v1.157.0 removed the deprecated, experimental MSC3861 auth delegation in favour of the stable MAS integration, so any environment still relying on that experimental path has to move before it upgrades past that release. Treat the change as a new authentication service with its own configuration, database and client registration in Keycloak, not a rename of a Synapse setting. Confirm the exact MAS and Synapse versions you will pair against in the MAS documentation before you schedule the cutover.

Existing users need a deliberate match to their upstream identities. Synapse stores each account under a Matrix user ID derived from the claims it received, while MAS links accounts to the subject (sub) of the upstream provider. Before cutover, export the list of Synapse users who signed in through Keycloak, confirm which Keycloak claim produced each Matrix localpart, and test that the same Keycloak user resolves to the same Matrix account under MAS. Mismatched mappings create duplicate accounts, orphaned rooms and lost device keys, so this is the step that most often needs a rehearsal in a staging copy of the database. Check the Matrix Authentication Service upstream SSO guide for the current mapping options before you write the claim templates.

Rollback is limited, so plan the migration as a one-way step unless you have tested otherwise. The Synapse upgrade notes warn that rolling back can be difficult because database schema changes between releases cannot always be reversed, and MAS adds its own tables. Take a consistent PostgreSQL backup of both databases immediately before cutover, record the Synapse and MAS versions, and rehearse restoring that backup on a separate host. Read the full set of Synapse upgrade notes for every release between your current version and the target. Matrix migration, upgrade and authentication steps should follow the Migrating to Matrix guidance, not an assumed configuration swap, and the cutover plan should be signed off by the people who own identity and data retention.

Questions buyers ask before connecting Matrix to Keycloak

How much effort does a Matrix and Keycloak SSO integration take?

Effort depends on which route you take and how much of the surrounding setup already exists. A Synapse integration uses the oidc_providers entry in the homeserver configuration, with a Keycloak client that has the correct redirect URI and a back-channel logout URL if you want sign-out to propagate. A Matrix Authentication Service (MAS) integration adds a second service to deploy, configure and keep running, plus its own upstream provider entry. The main drivers are the number of realms and clients in Keycloak, how user attributes map to Matrix IDs, whether existing Synapse password or SSO accounts must be kept, and how many environments need to be built and tested. Ask for a written list of those items before comparing quotes.

Can an internal team connect Keycloak to Matrix without a partner?

Yes, if the team already runs Keycloak and Synapse and has someone comfortable with OIDC claims, reverse proxies and homeserver configuration. The Synapse OpenID Connect guide and the MAS upstream SSO documentation describe the configuration steps. Teams without recent experience in one of those areas usually spend most of their time on troubleshooting claim mapping, redirect URIs and sign-out behavior, which is where an outside partner's time is most useful. Whichever route you take, plan for a staging environment and a documented rollback path before you change production sign-in.

What does the integration need from Keycloak and Matrix administrators?

The work is shared between the two teams. Keycloak administrators create a client for Matrix, set valid redirect URIs, define the scopes and claims the homeserver reads, and, for Synapse, enable back-channel logout with the URL that Synapse expects. Matrix administrators set the server_name, configure the oidc_providers entry or the MAS upstream provider, choose how claims map to localparts, and decide whether new SSO users are created automatically. Both teams need access to a test realm and a test homeserver, and someone must own the decision on who may sign in. Agree on that ownership before the build starts.

Should we choose Synapse OIDC or Matrix Authentication Service?

Choose based on where you want authentication to live. Synapse's oidc_providers setting keeps login inside the homeserver and is the simpler change for an existing Synapse deployment. MAS is an OAuth 2.0 and OpenID provider for Matrix that sits in front of the homeserver and delegates login to upstream providers such as Keycloak. Synapse v1.157.0 removed the deprecated experimental MSC3861 delegation in favor of the stable MAS integration, so teams that used the experimental path must plan a move. MAS does not support SAML, so if your Keycloak realm brokers a SAML identity provider, that brokering happens inside Keycloak and does not change the MAS constraint. Confirm these points against the current MAS and Synapse documentation for your version.

What does back-channel logout change for users and administrators?

Back-channel logout lets Keycloak notify Synapse server-side when a user signs out of Keycloak, so the Matrix session can end without relying on the browser. Synapse's Keycloak documentation describes this through backchannel_logout_enabled in the Synapse configuration and a back-channel logout URL in the Keycloak client. Test it with a real user across desktop and mobile clients, because sessions on devices that are offline at logout time behave differently. Also decide what happens to end-to-end encryption keys and device lists when sessions end, since users may lose access to history if they are not prepared.

How long will the integration take?

Duration depends on scope: the number of environments, the complexity of the Keycloak realm, whether MAS is added, how many existing accounts must be preserved, and how much testing your change process requires. No duration figure has been supplied for this topic, so ask any provider for a timeline tied to a written scope, with milestones for the staging build, user acceptance testing and the production cutover. Ask what the timeline assumes about your access to Keycloak and Matrix administrators, since waiting on those approvals often takes longer than the technical work.

What does a fixed-scope quote cover at DeployOpen?

DeployOpen works from a written scope agreed before work starts, and most engagements are fixed-scope. For this integration, the scope would typically name the route (Synapse OIDC or MAS), the Keycloak realm and client configuration, the claim mapping, the back-channel logout setup, the staging and production steps, the test cases and the handover documentation. Ask that the quote list what is excluded, such as LDAP or SAML brokering, bridges, or ongoing upgrades. DeployOpen does not publish a price list, so the quote follows from the written scope. Ongoing support, upgrades and continuous testing are available as retainers and would be quoted separately.

What should we keep in mind about Keycloak upgrades after go-live?

Keycloak releases a minor version several times a year, and breaking changes in minor releases are opt-in according to the project's October 2024 release notes. Keep the Matrix client configuration in version control so the redirect URIs and logout settings can be reproduced after an upgrade. Keycloak migrates its database schema automatically at startup by default, but the upgrading guide suggests manual migration for large deployments. Test sign-in and back-channel logout in staging after every Keycloak upgrade, and confirm the current supported database versions in the Keycloak database guide before you schedule changes.

How DeployOpen scopes and delivers Matrix and Keycloak SSO

DeployOpen plans, builds, documents and supports self-hosted Matrix and Keycloak sign-in inside your own infrastructure. We start from the choice between Synapse OIDC support and Matrix Authentication Service, then write the scope before any work begins so your security, identity and compliance teams can review it.

How we scope

  • Confirm which sign-in route fits your Synapse version, either Synapse oidc_providers or Matrix Authentication Service as an upstream provider setup
  • Record the Keycloak realm, client, redirect and back-channel logout design in the written scope before build starts
  • Engagements are fixed-scope, with deliverables and timelines agreed in writing; ongoing support is available as a retainer

How we build

  • Configure the Keycloak client, claim mapping to Matrix user IDs and the homeserver identity provider entry in your environment
  • Enable and test back-channel logout so a Keycloak sign-out ends the matching Synapse session
  • Test sign-in, account linking, access denial and logout paths, and document the results for your security review

How we hand over

  • Deliver configuration documentation covering the Synapse or MAS settings, Keycloak clients and the upgrade path for each component
  • Walk your platform and identity teams through runbooks for user lifecycle, provider changes and recovery
  • Provide evidence of configuration and test results that your compliance team can use in internal reviews and external assessments

How we support

  • Plan Keycloak and Synapse upgrades around their release notes, database requirements and rollback limits
  • Retest sign-in and logout after upgrades or identity provider changes under an agreed retainer
  • Keep operator guidance current as your Matrix deployment and identity estate change over time

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.