Keycloak SAML Security: Common Vulnerabilities and How to Harden Your Configuration
Last updated: March 2026
SAML remains one of the most widely deployed federation protocols in enterprise environments. It underpins single sign-on for thousands of applications across healthcare, government, financial services, and SaaS platforms. Keycloak, as both an Identity Provider (IdP) and a Service Provider (SP) broker, processes SAML assertions at scale, which makes its SAML implementation a high-value target for attackers.
The challenge with SAML is that its security model relies heavily on correct XML signature verification, proper certificate management, and strict assertion validation. A single misconfiguration or parser flaw can allow an attacker to forge assertions, hijack sessions, or exfiltrate data. This article examines the most critical SAML vulnerabilities affecting Keycloak deployments, explains the underlying attack mechanics, and provides concrete hardening steps you can apply today.
If you work with SAML assertions regularly, our SAML Decoder tool can help you inspect and debug assertions during development and troubleshooting.
CVE-2024-8698: SAML Signature Validation Bypass
CVE-2024-8698 is a high-severity vulnerability in Keycloak’s SAML signature validation logic, disclosed in September 2024. It affects how Keycloak verifies the cryptographic signatures on SAML responses and assertions, potentially allowing an attacker with low privileges to craft a malicious SAML response that bypasses signature verification entirely.
How the Vulnerability Works
The root cause is improper verification of SAML Response signatures. When Keycloak receives a SAML response, it must verify that the XML digital signature covers the exact assertions being processed. In vulnerable versions, Keycloak’s signature validation logic did not correctly bind the signature verification to the specific assertions within the response document. An attacker could manipulate the XML structure so that the signature validates against a different part of the document while Keycloak processes unsigned (and potentially tampered) assertions.
This class of vulnerability is particularly dangerous because the SAML response appears to pass all signature checks from the system’s perspective. Standard logging may not flag the discrepancy, making detection difficult without deep packet inspection of the SAML XML.
Affected Versions
The vulnerability affects Keycloak versions prior to the following patched releases:
- Keycloak 25.0.6 and earlier in the 25.x branch
- Keycloak 24.0.8 and earlier in the 24.x branch
- All versions of Red Hat build of Keycloak prior to the corresponding fixes
The CVSS v3.1 base score is 7.7 (High), reflecting the potential for authentication bypass with low attack complexity.
How to Check If You Are Vulnerable
First, verify your Keycloak version:
# Check Keycloak version via the admin CLI
/opt/keycloak/bin/kc.sh show-config | grep "Keycloak"
# Or check the admin console - the version displays at the bottom of the page
If you are running any SAML-based identity provider or service provider configurations in a pre-patch version, you are vulnerable. Review your realm’s Identity Providers section in the admin console. Any configured SAML IdPs or SPs using XML signature validation are affected.
Mitigation Steps
The primary mitigation is upgrading to a patched version of Keycloak. If you are on Skycloak’s managed hosting platform, this patch was applied automatically during our regular security update cycle.
For self-managed deployments:
- Upgrade immediately to Keycloak 25.0.7+ or 24.0.9+, depending on your branch.
- Enforce full signature validation on both the SAML response and individual assertions. In the Keycloak admin console, navigate to your SAML client or Identity Provider configuration and verify that
Want Assertions SignedandWant AuthnRequests Signedare both enabled. - Review audit logs for unusual SAML authentication events, particularly any successful authentications from unexpected sources or with anomalous assertion attributes.
<!-- In your SAML SP metadata, ensure these attributes are set -->
<SPSSODescriptor
AuthnRequestsSigned="true"
WantAssertionsSigned="true"
protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
XML Signature Wrapping Attacks
XML Signature Wrapping (XSW) is a class of attacks that exploits the separation between XML signature verification and XML document processing. Rather than breaking the cryptographic signature itself, the attacker manipulates the XML document structure so that the signature validates correctly but the application processes a different, attacker-controlled element.
Attack Mechanics
In a typical XSW attack against a SAML implementation:
- The attacker intercepts a legitimate SAML response containing a valid signature.
- They move the signed assertion to a location in the XML tree where the signature still validates (such as wrapping it in an extensions element).
- They insert a forged assertion in the original location where the application expects to find it.
- The signature verification passes because the signed element is still present and intact. The application then processes the forged assertion because it reads from the expected XML path.
There are multiple variants of XSW attacks (XSW1 through XSW8), each targeting different combinations of how IdPs and SPs locate and verify signed elements within the SAML XML structure.
How Keycloak Protects Against XSW
Keycloak’s SAML processing stack includes protections against known XSW variants. Specifically, it performs reference validation to ensure that the signature’s reference URI points to the same element that is being processed as the assertion. The XML parser is configured to resolve element references strictly, preventing the signature from validating against a relocated copy of the assertion.
However, these protections are only effective when signature validation is properly configured and enforced. A misconfigured Keycloak deployment that does not require signed assertions is inherently vulnerable to assertion manipulation regardless of XSW protections.
Configuration to Enforce Protection
In the Keycloak admin console, for each SAML client:
- Navigate to Clients and select your SAML client.
- Under the Settings tab, ensure
Sign Assertionsis set to ON. - Set
Signature Algorithmto RSA_SHA256 at minimum (avoid SHA1, which is deprecated). - Under the Keys tab, verify the signing certificate is current and uses at least a 2048-bit RSA key or an ECDSA key.
For Identity Provider configurations (when Keycloak acts as SP):
- Navigate to Identity Providers and select your SAML IdP.
- Enable
Validate Signaturesto ON. - Enable
Want Assertions Signedto ON. - Import the IdP’s signing certificate under the Keys tab.
SAML Assertion Replay Attacks
A replay attack occurs when an attacker captures a valid SAML assertion and resubmits it to gain unauthorized access. Because SAML assertions are bearer tokens, anyone who possesses a valid assertion can present it to a service provider and authenticate as the original user, unless proper replay protections are in place.
Attack Scenario
- An attacker intercepts a SAML assertion in transit (via network sniffing, log exposure, or a compromised browser).
- The attacker submits the captured assertion to the service provider’s Assertion Consumer Service (ACS) endpoint.
- If the SP does not track previously consumed assertions or enforce time-based validity, the attacker gains a valid session.
Keycloak’s Built-In Protections
Keycloak implements several mechanisms to prevent assertion replay:
- NotOnOrAfter conditions: Every assertion includes a
Conditionselement withNotBeforeandNotOnOrAftertimestamps that define a strict validity window. Keycloak enforces these timestamps during assertion validation, rejecting assertions outside their validity period. - InResponseTo tracking: For SP-initiated flows, Keycloak tracks the
InResponseToattribute linking the assertion to a specific authentication request. An assertion that does not correspond to a pending authentication request is rejected. - Session binding: Once an assertion is consumed and a session is created, Keycloak does not accept the same assertion for a new session.
Hardening Session and Assertion Timeouts
The default assertion validity window in Keycloak is relatively generous. Tightening these values reduces the window of opportunity for replay:
- Navigate to Realm Settings and then Tokens.
- Set
Access Token Lifespanto the shortest practical value for your use case (e.g., 5 minutes). - Under Sessions, set
SSO Session IdleandSSO Session Maxto appropriate values. For high-security environments, consider 15 minutes idle and 8 hours maximum. - For SAML-specific settings, configure the
Assertion Lifespanin the SAML client settings. A value of 60-180 seconds is typically sufficient for the assertion to be transmitted and consumed.
Monitor for replay attempts by reviewing authentication events in your security logs. Failed assertions due to expired conditions or mismatched InResponseTo values may indicate replay attempts.
Certificate Management
SAML security is fundamentally dependent on the integrity of the signing and encryption certificates. Compromised, expired, or improperly rotated certificates can cause service outages or create security gaps that attackers can exploit.
Certificate Rotation Without Downtime
Keycloak supports multiple active key pairs per realm, which enables zero-downtime certificate rotation:
- In Realm Settings, navigate to the Keys tab.
- Click Providers and add a new
rsa-generatedorrsakey provider with a higher priority than the existing one. - Keycloak will immediately begin signing new SAML assertions and responses with the new key.
- The old key remains available for verification, so assertions signed with the previous key are still accepted during the transition period.
- Update your SPs with the new signing certificate (available from the realm’s SAML metadata endpoint at
/realms/{realm}/protocol/saml/descriptor). - After all SPs have updated their trust stores, disable or remove the old key provider.
Key Pair Management Best Practices
- Use RSA 2048-bit keys at minimum. For new deployments, 3072-bit or 4096-bit RSA keys provide a better security margin. ECDSA P-256 keys are also supported and offer equivalent security with smaller key sizes.
- Separate signing and encryption keys. Keycloak allows distinct key pairs for different purposes. Use one key pair for signing assertions and a separate pair for encrypting assertions.
- Set key rotation schedules. Rotate SAML signing keys at least annually, or more frequently in regulated environments. Skycloak’s managed platform can handle this automatically as part of your security configuration.
- Never export private keys from production Keycloak instances. If you need the same key across a cluster, use a shared database or vault-backed key provider.
Monitoring Certificate Expiry
Certificate expiry is one of the most common causes of SAML authentication failures. Implement monitoring that alerts before certificates expire:
# Check certificate expiry from Keycloak's SAML metadata
curl -s https://your-keycloak.example.com/realms/your-realm/protocol/saml/descriptor
| xmllint --xpath "//*[local-name()='X509Certificate']/text()" -
| base64 -d
| openssl x509 -noout -enddate
Set alerts for at least 30 days before expiry to allow time for coordinated rotation across all relying parties.
XML External Entity (XXE) Attacks
XXE attacks exploit XML parsers that process external entity references within XML documents. In the context of SAML, an attacker could craft a malicious SAML response or assertion containing external entity declarations that, when parsed, cause the server to read local files, make outbound network requests, or exhaust resources.
Attack Example
A malicious SAML response might include:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<samlp:Response>
<!-- Assertion with &xxe; reference that expands to file contents -->
</samlp:Response>
If the XML parser processes the external entity, the contents of /etc/passwd (or any other accessible file) would be injected into the parsed document, potentially leaking sensitive data back to the attacker through error messages or attribute values.
Keycloak’s XML Parser Protections
Keycloak’s SAML processing uses a hardened XML parser configuration that disables external entity processing by default. Specifically:
DocumentBuilderFactoryis configured withFEATURE_SECURE_PROCESSINGenabled.- External DTDs and external general entities are disabled (
http://apache.org/xml/features/disallow-doctype-declis set to true in the SAML parser). - The parser does not resolve external references, preventing both file-based and network-based XXE attacks.
Verifying Your Setup
If you are running Keycloak behind a reverse proxy or load balancer that performs XML processing (such as an XML gateway or WAF with XML inspection), verify that those components also have XXE protections enabled. The entire chain from the client to Keycloak must be hardened.
For self-hosted deployments, you can verify the parser configuration by attempting to send a SAML response with an entity declaration to your ACS endpoint. A properly configured Keycloak instance will reject the document at the parser level before any SAML processing occurs.
Review our documentation for additional guidance on securing your Keycloak infrastructure, including network-level protections that complement these application-level safeguards.
IdP-Initiated vs SP-Initiated Flows: Security Implications
SAML supports two authentication flow patterns, and they carry very different security profiles. Understanding these differences is critical for hardening your deployment.
SP-Initiated Flow (More Secure)
In SP-initiated SSO, the service provider generates an AuthnRequest with a unique ID, sends the user to the IdP, and then validates that the returning assertion’s InResponseTo attribute matches the original request ID. This creates a cryptographic binding between the request and response that prevents unsolicited assertion injection.
IdP-Initiated Flow (Less Secure)
In IdP-initiated SSO, the IdP sends an unsolicited assertion to the SP without a preceding AuthnRequest. Because there is no InResponseTo binding, the SP cannot verify that the assertion was generated in response to a legitimate authentication attempt. This opens the door to:
- Assertion injection: An attacker who obtains or forges an assertion can submit it directly to the SP’s ACS endpoint.
- Replay attacks: Without request-response correlation, replay detection is limited to time-based validity checks only.
- Cross-site request forgery: An attacker can construct a page that auto-submits a SAML response to the SP’s ACS endpoint.
When You Must Support IdP-Initiated and How to Limit Exposure
Some legacy enterprise applications require IdP-initiated flows. If you must support them:
- Restrict the Assertion Consumer Service URL to a single, specific endpoint. Do not accept wildcards or multiple ACS URLs for IdP-initiated flows.
- Set the shortest practical assertion validity (60 seconds or less if your network conditions allow).
- Implement one-time assertion consumption on the SP side. Track assertion IDs and reject any assertion that has already been consumed.
- Use encrypted assertions so that intercepted assertions cannot be read or replayed by intermediaries.
- Log and monitor all IdP-initiated authentications separately. An unexpected spike in IdP-initiated logins can indicate an attack. Use Skycloak’s audit logs to track these events.
Hardening Checklist
Use this checklist to systematically harden your Keycloak SAML configuration. Each item addresses a specific attack vector discussed in this article.
Signature Validation
- [ ] Enable
Want Assertions Signedon all SAML clients and Identity Providers - [ ] Enable
Want AuthnRequests Signedfor SP configurations - [ ] Set signature algorithm to RSA_SHA256 or stronger (never SHA1)
- [ ] Verify that signature validation is enforced at both the response and assertion level
- [ ] Upgrade to Keycloak 25.0.7+ or 24.0.9+ to patch CVE-2024-8698
Assertion Security
- [ ] Set assertion lifespan to 60-180 seconds
- [ ] Configure SSO session idle timeout (15 minutes recommended for high-security environments)
- [ ] Configure SSO session maximum lifespan (8-10 hours)
- [ ] Enable encrypted assertions for clients that support it
- [ ] Restrict Assertion Consumer Service URLs to exact-match values (no wildcards)
Certificate Management
- [ ] Use RSA 2048-bit keys or stronger for all SAML signing operations
- [ ] Separate signing and encryption key pairs
- [ ] Implement certificate expiry monitoring with 30-day advance alerts
- [ ] Document and test the certificate rotation procedure
- [ ] Rotate signing keys at least annually
Protocol and Flow Security
- [ ] Prefer SP-initiated flows over IdP-initiated flows
- [ ] If IdP-initiated flows are required, implement one-time assertion consumption
- [ ] Verify XML parser configuration disables external entity processing
- [ ] Ensure
Force POST Bindingis enabled to prevent assertion leakage in URL parameters
Monitoring and Incident Response
- [ ] Monitor security events for failed SAML authentications
- [ ] Set up alerts for signature validation failures (potential XSW or CVE exploitation)
- [ ] Log and review all IdP-initiated authentication events
- [ ] Maintain an incident response runbook for SAML-related security events
- [ ] Keep Keycloak updated to the latest patch version
Conclusion
SAML security in Keycloak is not a set-and-forget configuration. The protocol’s reliance on XML processing, cryptographic signatures, and certificate trust chains creates a broad attack surface that requires ongoing attention. From CVE-2024-8698’s signature validation bypass to XML wrapping attacks and assertion replay, each vulnerability targets a specific aspect of the SAML trust model.
The most effective defense is layered: keep Keycloak patched to address known CVEs, enforce strict signature validation on all assertions and responses, manage certificates with proper rotation schedules, prefer SP-initiated flows where possible, and monitor authentication events for anomalies.
If you are running Keycloak in production with SAML integrations, use the hardening checklist above as a starting point for a security review. For teams that want these protections managed and monitored continuously, Skycloak’s managed Keycloak platform handles patching, certificate management, and security monitoring so you can focus on building your applications.
Ready to simplify your authentication?
Deploy production-ready Keycloak in minutes. Unlimited users, flat pricing, no SSO tax.