From 9135ba7c402de35e09e71f234b83e0c9ca871604 Mon Sep 17 00:00:00 2001 From: Hisanobu Okuda Date: Mon, 29 May 2017 16:24:36 +0900 Subject: [PATCH] KEYCLOAK-4980 SAML adapter should return 401 when unauthenticated Ajax client accesses --- .../adapters/saml/DefaultSamlDeployment.java | 10 + .../adapters/saml/SamlDeployment.java | 2 +- .../org/keycloak/adapters/saml/config/SP.java | 8 + .../config/parsers/ConfigXmlConstants.java | 1 + .../config/parsers/DeploymentBuilder.java | 1 + .../saml/config/parsers/SPXmlParser.java | 1 + .../AbstractSamlAuthenticationHandler.java | 42 +- .../schema/keycloak_saml_adapter_1_9.xsd | 461 ++++++++++++++++++ .../KeycloakSamlAdapterXMLParserTest.java | 3 +- .../saml/config/parsers/keycloak-saml.xml | 4 +- .../page/SalesPostAutodetectServlet.java | 39 ++ .../AbstractSAMLServletsAdapterTest.java | 56 +++ .../WEB-INF/keycloak-saml.xml | 44 ++ 13 files changed, 665 insertions(+), 7 deletions(-) create mode 100644 adapters/saml/core/src/main/resources/schema/keycloak_saml_adapter_1_9.xsd create mode 100644 testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/adapter/page/SalesPostAutodetectServlet.java create mode 100755 testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-autodetect/WEB-INF/keycloak-saml.xml diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/DefaultSamlDeployment.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/DefaultSamlDeployment.java index d92884fd5d..9a6e2880ec 100755 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/DefaultSamlDeployment.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/DefaultSamlDeployment.java @@ -294,6 +294,7 @@ public class DefaultSamlDeployment implements SamlDeployment { private String logoutPage; private SignatureAlgorithm signatureAlgorithm; private String signatureCanonicalizationMethod; + private boolean autodetectBearerOnly; @Override public boolean turnOffChangeSessionIdOnLogin() { @@ -439,4 +440,13 @@ public class DefaultSamlDeployment implements SamlDeployment { public void setSignatureAlgorithm(SignatureAlgorithm signatureAlgorithm) { this.signatureAlgorithm = signatureAlgorithm; } + + @Override + public boolean isAutodetectBearerOnly() { + return autodetectBearerOnly; + } + + public void setAutodetectBearerOnly(boolean autodetectBearerOnly) { + this.autodetectBearerOnly = autodetectBearerOnly; + } } diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/SamlDeployment.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/SamlDeployment.java index a9df7e9461..0b7ac40ecf 100755 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/SamlDeployment.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/SamlDeployment.java @@ -168,6 +168,6 @@ public interface SamlDeployment { } PrincipalNamePolicy getPrincipalNamePolicy(); String getPrincipalAttributeName(); - + boolean isAutodetectBearerOnly(); } diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/SP.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/SP.java index 475a0f491c..071b170d2f 100755 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/SP.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/SP.java @@ -58,6 +58,7 @@ public class SP implements Serializable { private PrincipalNameMapping principalNameMapping; private Set roleAttributes; private IDP idp; + private boolean autodetectBearerOnly; public String getEntityID() { return entityID; @@ -147,4 +148,11 @@ public class SP implements Serializable { this.logoutPage = logoutPage; } + public boolean isAutodetectBearerOnly() { + return autodetectBearerOnly; + } + + public void setAutodetectBearerOnly(boolean autodetectBearerOnly) { + this.autodetectBearerOnly = autodetectBearerOnly; + } } diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/ConfigXmlConstants.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/ConfigXmlConstants.java index 256bfa2a97..ecde04a3fc 100755 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/ConfigXmlConstants.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/ConfigXmlConstants.java @@ -33,6 +33,7 @@ public class ConfigXmlConstants { public static final String SIGNATURE_ALGORITHM_ATTR = "signatureAlgorithm"; public static final String SIGNATURE_CANONICALIZATION_METHOD_ATTR = "signatureCanonicalizationMethod"; public static final String LOGOUT_PAGE_ATTR = "logoutPage"; + public static final String AUTODETECT_BEARER_ONLY_ATTR = "autodetectBearerOnly"; public static final String KEYS_ELEMENT = "Keys"; public static final String KEY_ELEMENT = "Key"; diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/DeploymentBuilder.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/DeploymentBuilder.java index b5f8abad22..92254a2483 100755 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/DeploymentBuilder.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/DeploymentBuilder.java @@ -68,6 +68,7 @@ public class DeploymentBuilder { deployment.setNameIDPolicyFormat(sp.getNameIDPolicyFormat()); deployment.setLogoutPage(sp.getLogoutPage()); deployment.setSignatureCanonicalizationMethod(sp.getIdp().getSignatureCanonicalizationMethod()); + deployment.setAutodetectBearerOnly(sp.isAutodetectBearerOnly()); deployment.setSignatureAlgorithm(SignatureAlgorithm.RSA_SHA256); if (sp.getIdp().getSignatureAlgorithm() != null) { deployment.setSignatureAlgorithm(SignatureAlgorithm.valueOf(sp.getIdp().getSignatureAlgorithm())); diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/SPXmlParser.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/SPXmlParser.java index be6d682705..57d5f58f62 100755 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/SPXmlParser.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/SPXmlParser.java @@ -89,6 +89,7 @@ public class SPXmlParser extends AbstractParser { sp.setNameIDPolicyFormat(getAttributeValue(startElement, ConfigXmlConstants.NAME_ID_POLICY_FORMAT_ATTR)); sp.setForceAuthentication(getBooleanAttributeValue(startElement, ConfigXmlConstants.FORCE_AUTHENTICATION_ATTR)); sp.setIsPassive(getBooleanAttributeValue(startElement, ConfigXmlConstants.IS_PASSIVE_ATTR)); + sp.setAutodetectBearerOnly(getBooleanAttributeValue(startElement, ConfigXmlConstants.AUTODETECT_BEARER_ONLY_ATTR)); sp.setTurnOffChangeSessionIdOnLogin(getBooleanAttributeValue(startElement, ConfigXmlConstants.TURN_OFF_CHANGE_SESSSION_ID_ON_LOGIN_ATTR)); while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader); diff --git a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/profile/AbstractSamlAuthenticationHandler.java b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/profile/AbstractSamlAuthenticationHandler.java index 5721b038a9..16135937d3 100644 --- a/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/profile/AbstractSamlAuthenticationHandler.java +++ b/adapters/saml/core/src/main/java/org/keycloak/adapters/saml/profile/AbstractSamlAuthenticationHandler.java @@ -568,9 +568,15 @@ public abstract class AbstractSamlAuthenticationHandler implements SamlAuthentic return new AbstractInitiateLogin(deployment, sessionStore) { @Override protected void sendAuthnRequest(HttpFacade httpFacade, SAML2AuthnRequestBuilder authnRequestBuilder, BaseSAML2BindingBuilder binding) throws ProcessingException, ConfigurationException, IOException { - Document document = authnRequestBuilder.toDocument(); - SamlDeployment.Binding samlBinding = deployment.getIDP().getSingleSignOnService().getRequestBinding(); - SamlUtil.sendSaml(true, httpFacade, deployment.getIDP().getSingleSignOnService().getRequestBindingUrl(), binding, document, samlBinding); + if (isAutodetectedBearerOnly(httpFacade.getRequest())) { + httpFacade.getResponse().setStatus(401); + httpFacade.getResponse().end(); + } + else { + Document document = authnRequestBuilder.toDocument(); + SamlDeployment.Binding samlBinding = deployment.getIDP().getSingleSignOnService().getRequestBinding(); + SamlUtil.sendSaml(true, httpFacade, deployment.getIDP().getSingleSignOnService().getRequestBindingUrl(), binding, document, samlBinding); + } } }; } @@ -693,4 +699,34 @@ public abstract class AbstractSamlAuthenticationHandler implements SamlAuthentic return signature.verify(decodedSignature); } + + protected boolean isAutodetectedBearerOnly(HttpFacade.Request request) { + if (!deployment.isAutodetectBearerOnly()) return false; + + String headerValue = facade.getRequest().getHeader(GeneralConstants.HTTP_HEADER_X_REQUESTED_WITH); + if (headerValue != null && headerValue.equalsIgnoreCase("XMLHttpRequest")) { + return true; + } + + headerValue = facade.getRequest().getHeader("Faces-Request"); + if (headerValue != null && headerValue.startsWith("partial/")) { + return true; + } + + headerValue = facade.getRequest().getHeader("SOAPAction"); + if (headerValue != null) { + return true; + } + + List accepts = facade.getRequest().getHeaders("Accept"); + if (accepts == null) accepts = Collections.emptyList(); + + for (String accept : accepts) { + if (accept.contains("text/html") || accept.contains("text/*") || accept.contains("*/*")) { + return false; + } + } + + return true; + } } diff --git a/adapters/saml/core/src/main/resources/schema/keycloak_saml_adapter_1_9.xsd b/adapters/saml/core/src/main/resources/schema/keycloak_saml_adapter_1_9.xsd new file mode 100644 index 0000000000..cf9c05c4a7 --- /dev/null +++ b/adapters/saml/core/src/main/resources/schema/keycloak_saml_adapter_1_9.xsd @@ -0,0 +1,461 @@ + + + + + + + + + + Keycloak SAML Adapter configuration file. + + + + + Describes SAML service provider configuration. + + + + + + + + + + + List of service provider encryption and validation keys. + + If the IDP requires that the client application (SP) sign all of its requests and/or if the IDP will encrypt assertions, you must define the keys used to do this. For client signed documents you must define both the private and public key or certificate that will be used to sign documents. For encryption, you only have to define the private key that will be used to decrypt. + + + + + When creating a Java Principal object that you obtain from methods like HttpServletRequest.getUserPrincipal(), you can define what name that is returned by the Principal.getName() method. + + + + + Defines what SAML attributes within the assertion received from the user should be used as role identifiers within the Java EE Security Context for the user. + By default Role attribute values are converted to Java EE roles. Some IDPs send roles via a member or memberOf attribute assertion. You can define one or more Attribute elements to specify which SAML attributes must be converted into roles. + + + + + Describes configuration of SAML identity provider for this service provider. + + + + + + This is the identifier for this client. The IDP needs this value to determine who the client is that is communicating with it. + + + + + SSL policy the adapter will enforce. + + + + + SAML clients can request a specific NameID Subject format. Fill in this value if you want a specific format. It must be a standard SAML format identifier, i.e. urn:oasis:names:tc:SAML:2.0:nameid-format:transient. By default, no special format is requested. + + + + + URL of the logout page. + + + + + SAML clients can request that a user is re-authenticated even if they are already logged in at the IDP. Default value is false. + + + + + SAML clients can request that a user is never asked to authenticate even if they are not logged in at the IDP. Set this to true if you want this. Do not use together with forceAuthentication as they are opposite. Default value is false. + + + + + The session id is changed by default on a successful login on some platforms to plug a security attack vector. Change this to true to disable this. It is recommended you do not turn it off. Default value is false. + + + + + This should be set to true if your application serves both a web application and web services (e.g. SOAP or REST). It allows you to redirect unauthenticated users of the web application to the Keycloak login page, but send an HTTP 401 status code to unauthenticated SOAP or REST clients instead as they would not understand a redirect to the login page. Keycloak auto-detects SOAP or REST clients based on typical headers like X-Requested-With, SOAPAction or Accept. The default value is false. + + + + + + + + + Describes a single key used for signing or encryption. + + + + + + + + + Java keystore to load keys and certificates from. + + + + + Private key (PEM format) + + + + + Public key (PEM format) + + + + + Certificate key (PEM format) + + + + + + Flag defining whether the key should be used for signing. + + + + + Flag defining whether the key should be used for encryption + + + + + + + + Private key declaration + + + + + Certificate declaration + + + + + + File path to the key store. + + + + + WAR resource path to the key store. This is a path used in method call to ServletContext.getResourceAsStream(). + + + + + The password of the key store. + + + + + + + Alias that points to the key or cert within the keystore. + + + + + Keystores require an additional password to access private keys. In the PrivateKey element you must define this password within a password attribute. + + + + + + + Alias that points to the key or cert within the keystore. + + + + + + + Policy used to populate value of Java Principal object obtained from methods like HttpServletRequest.getUserPrincipal(). + + + + + Name of the SAML assertion attribute to use within. + + + + + + + + This policy just uses whatever the SAML subject value is. This is the default setting + + + + + This will pull the value from one of the attributes declared in the SAML assertion received from the server. You'll need to specify the name of the SAML assertion attribute to use within the attribute XML attribute. + + + + + + + + + All requests must come in via HTTPS. + + + + + Only non-private IP addresses must come over the wire via HTTPS. + + + + + no requests are required to come over via HTTPS. + + + + + + + + + + + + + + + + + + + + + + + Specifies SAML attribute to be converted into roles. + + + + + + + + Specifies name of the SAML attribute to be converted into roles. + + + + + + + + Configuration of the login SAML endpoint of the IDP. + + + + + Configuration of the logout SAML endpoint of the IDP + + + + + The Keys sub element of IDP is only used to define the certificate or public key to use to verify documents signed by the IDP. + + + + + Configuration of HTTP client used for automatic obtaining of certificates containing public keys for IDP signature verification via SAML descriptor of the IDP. + + + + + + issuer ID of the IDP. + + + + + If set to true, the client adapter will sign every document it sends to the IDP. Also, the client will expect that the IDP will be signing any documents sent to it. This switch sets the default for all request and response types. + + + + + Signature algorithm that the IDP expects signed documents to use. Defaults to RSA_SHA256 + + + + + This is the signature canonicalization method that the IDP expects signed documents to use. The default value is https://www.w3.org/2001/10/xml-exc-c14n# and should be good for most IDPs. + + + + + + + + + + + + Should the client sign authn requests? Defaults to whatever the IDP signaturesRequired element value is. + + + + + Should the client expect the IDP to sign the assertion response document sent back from an auhtn request? Defaults to whatever the IDP signaturesRequired element value is. + + + + + Should the client expect the IDP to sign the individual assertions sent back from an auhtn request? Defaults to whatever the IDP signaturesRequired element value is. + + + + + SAML binding type used for communicating with the IDP. The default value is POST, but you can set it to REDIRECT as well. + + + + + SAML allows the client to request what binding type it wants authn responses to use. This value maps to ProtocolBinding attribute in SAML AuthnRequest. The default is that the client will not request a specific binding type for responses. + + + + + This is the URL for the IDP login service that the client will send requests to. + + + + + URL of the assertion consumer service (ACS) where the IDP login service should send responses to. By default it is unset, relying on the IdP settings. When set, it must end in "/saml". This property is typically accompanied by the responseBinding attribute. + + + + + + + + Should the client sign authn requests? Defaults to whatever the IDP signaturesRequired element value is. + + + + + Should the client sign logout responses it sends to the IDP requests? Defaults to whatever the IDP signaturesRequired element value is. + + + + + Should the client expect signed logout request documents from the IDP? Defaults to whatever the IDP signaturesRequired element value is. + + + + + Should the client expect signed logout response documents from the IDP? Defaults to whatever the IDP signaturesRequired element value is. + + + + + This is the SAML binding type used for communicating SAML requests to the IDP. The default value is POST. + + + + + This is the SAML binding type used for communicating SAML responses to the IDP. The default value is POST. + + + + + This is the URL for the IDP's logout service when using the POST binding. This setting is REQUIRED if using the POST binding. + + + + + This is the URL for the IDP's logout service when using the REDIRECT binding. This setting is REQUIRED if using the REDIRECT binding. + + + + + + + + If the the IDP server requires HTTPS and this config option is set to true the IDP's certificate + is validated via the truststore, but host name validation is not done. This setting should only be used during + development and never in production as it will partly disable verification of SSL certificates. + This seting may be useful in test environments. The default value is false. + + + + + This is the file path to a keystore file. This keystore contains client certificate + for two-way SSL when the adapter makes HTTPS requests to the IDP server. + + + + + Password for the client keystore and for the client's key. + + + + + Defines number of pooled connections. + + + + + If the the IDP server requires HTTPS and this config option is set to true you do not have to specify a truststore. + This setting should only be used during development and never in production as it will disable verification of SSL certificates. + The default value is false. + + + + + URL to HTTP proxy to use for HTTP connections. + + + + + The value is the file path to a keystore file. If you prefix the path with classpath:, + then the truststore will be obtained from the deployment's classpath instead. Used for outgoing + HTTPS communications to the IDP server. Client making HTTPS requests need + a way to verify the host of the server they are talking to. This is what the trustore does. + The keystore contains one or more trusted host certificates or certificate authorities. + You can create this truststore by extracting the public certificate of the IDP's SSL keystore. + + + + + + Password for the truststore keystore. + + + + + diff --git a/adapters/saml/core/src/test/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterXMLParserTest.java b/adapters/saml/core/src/test/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterXMLParserTest.java index b64f181dcc..88a96cb142 100755 --- a/adapters/saml/core/src/test/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterXMLParserTest.java +++ b/adapters/saml/core/src/test/java/org/keycloak/adapters/saml/config/parsers/KeycloakSamlAdapterXMLParserTest.java @@ -37,7 +37,7 @@ import org.keycloak.saml.common.exceptions.ParsingException; */ public class KeycloakSamlAdapterXMLParserTest { - private static final String CURRENT_XSD_LOCATION = "/schema/keycloak_saml_adapter_1_7.xsd"; + private static final String CURRENT_XSD_LOCATION = "/schema/keycloak_saml_adapter_1_9.xsd"; @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -91,6 +91,7 @@ public class KeycloakSamlAdapterXMLParserTest { assertEquals("format", sp.getNameIDPolicyFormat()); assertTrue(sp.isForceAuthentication()); assertTrue(sp.isIsPassive()); + assertFalse(sp.isAutodetectBearerOnly()); assertEquals(2, sp.getKeys().size()); Key signing = sp.getKeys().get(0); assertTrue(signing.isSigning()); diff --git a/adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml.xml b/adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml.xml index 193525a894..31f62e5856 100755 --- a/adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml.xml +++ b/adapters/saml/core/src/test/resources/org/keycloak/adapters/saml/config/parsers/keycloak-saml.xml @@ -17,7 +17,7 @@ + xsi:schemaLocation="urn:keycloak:saml:adapter http://www.keycloak.org/schema/keycloak_saml_adapter_1_9.xsd"> - \ No newline at end of file + diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/adapter/page/SalesPostAutodetectServlet.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/adapter/page/SalesPostAutodetectServlet.java new file mode 100644 index 0000000000..9e7e3b7ac6 --- /dev/null +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/adapter/page/SalesPostAutodetectServlet.java @@ -0,0 +1,39 @@ +/* + * Copyright 2016 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.keycloak.testsuite.adapter.page; + +import org.jboss.arquillian.container.test.api.OperateOnDeployment; +import org.jboss.arquillian.test.api.ArquillianResource; + +import java.net.URL; + +/** + * @author mhajas + */ +public class SalesPostAutodetectServlet extends SAMLServlet { + public static final String DEPLOYMENT_NAME = "sales-post-autodetect"; + + @ArquillianResource + @OperateOnDeployment(DEPLOYMENT_NAME) + private URL url; + + @Override + public URL getInjectedUrl() { + return url; + } +} diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/AbstractSAMLServletsAdapterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/AbstractSAMLServletsAdapterTest.java index ecf48bf850..420fad8c48 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/AbstractSAMLServletsAdapterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/AbstractSAMLServletsAdapterTest.java @@ -198,6 +198,9 @@ public abstract class AbstractSAMLServletsAdapterTest extends AbstractServletsAd @Page private SAMLIDPInitiatedLogin samlidpInitiatedLoginPage; + @Page + protected SalesPostAutodetectServlet salesPostAutodetectServletPage; + public static final String FORBIDDEN_TEXT = "HTTP status code: 403"; @Deployment(name = BadClientSalesPostSigServlet.DEPLOYMENT_NAME) @@ -325,6 +328,11 @@ public abstract class AbstractSAMLServletsAdapterTest extends AbstractServletsAd return samlServletDeployment(EmployeeServlet.DEPLOYMENT_NAME, "employee/WEB-INF/web.xml", SamlSPFacade.class, ServletTestUtils.class); } + @Deployment(name = SalesPostAutodetectServlet.DEPLOYMENT_NAME) + protected static WebArchive salesPostAutodetect() { + return samlServletDeployment(SalesPostAutodetectServlet.DEPLOYMENT_NAME, SendUsernameServlet.class); + } + @Override public void addAdapterTestRealms(List testRealms) { testRealms.add(loadRealm("/adapter-test/keycloak-saml/testsaml.json")); @@ -1115,6 +1123,54 @@ public abstract class AbstractSAMLServletsAdapterTest extends AbstractServletsAd checkLoggedOut(differentCookieNameServletPage, testRealmSAMLPostLoginPage); } + @Test + /* KEYCLOAK-4980 */ + public void testAutodetectBearerOnly() throws Exception { + Client client = ClientBuilder.newClient(); + + // Do not redirect client to login page if it's an XHR + WebTarget target = client.target(salesPostAutodetectServletPage.toString()); + Response response = target.request().header("X-Requested-With", "XMLHttpRequest").get(); + Assert.assertEquals(401, response.getStatus()); + response.close(); + + // Do not redirect client to login page if it's a partial Faces request + response = target.request().header("Faces-Request", "partial/ajax").get(); + Assert.assertEquals(401, response.getStatus()); + response.close(); + + // Do not redirect client to login page if it's a SOAP request + response = target.request().header("SOAPAction", "").get(); + Assert.assertEquals(401, response.getStatus()); + response.close(); + + // Do not redirect client to login page if Accept header is missing + response = target.request().get(); + Assert.assertEquals(401, response.getStatus()); + response.close(); + + // Do not redirect client to login page if client does not understand HTML reponses + response = target.request().header(HttpHeaders.ACCEPT, "application/json,text/xml").get(); + Assert.assertEquals(401, response.getStatus()); + response.close(); + + // Redirect client to login page if it's not an XHR + response = target.request().header("X-Requested-With", "Dont-Know").header(HttpHeaders.ACCEPT, "*/*").get(); + Assert.assertEquals(200, response.getStatus()); + response.close(); + + // Redirect client to login page if client explicitely understands HTML responses + response = target.request().header(HttpHeaders.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9").get(); + Assert.assertEquals(200, response.getStatus()); + response.close(); + + // Redirect client to login page if client understands all response types + response = target.request().header(HttpHeaders.ACCEPT, "*/*").get(); + Assert.assertEquals(200, response.getStatus()); + response.close(); + client.close(); + } + private URI getAuthServerSamlEndpoint(String realm) throws IllegalArgumentException, UriBuilderException { return RealmsResource .protocolUrl(UriBuilder.fromUri(getAuthServerRoot())) diff --git a/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-autodetect/WEB-INF/keycloak-saml.xml b/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-autodetect/WEB-INF/keycloak-saml.xml new file mode 100755 index 0000000000..b00a1c0624 --- /dev/null +++ b/testsuite/integration-arquillian/tests/base/src/test/resources/adapter-test/keycloak-saml/sales-post-autodetect/WEB-INF/keycloak-saml.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + +