Search in sources :

Example 11 with ParsingException

use of org.keycloak.saml.common.exceptions.ParsingException in project keycloak by keycloak.

the class StaxParserUtil method validate.

public static void validate(InputStream doc, InputStream sch) throws ParsingException {
    try {
        XMLEventReader xmlEventReader = StaxParserUtil.getXMLEventReader(doc);
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(sch));
        Validator validator = schema.newValidator();
        StAXSource stAXSource = new StAXSource(xmlEventReader);
        validator.validate(stAXSource);
    } catch (Exception e) {
        throw logger.parserException(e);
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) XMLEventReader(javax.xml.stream.XMLEventReader) StAXSource(javax.xml.transform.stax.StAXSource) Validator(javax.xml.validation.Validator) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) XMLStreamException(javax.xml.stream.XMLStreamException) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException)

Example 12 with ParsingException

use of org.keycloak.saml.common.exceptions.ParsingException in project keycloak by keycloak.

the class SAML2LogoutResponseBuilder method buildDocument.

public Document buildDocument() throws ProcessingException {
    Document samlResponse = null;
    try {
        StatusResponseType statusResponse = buildModel();
        SAML2Response saml2Response = new SAML2Response();
        samlResponse = saml2Response.convert(statusResponse);
    } catch (ConfigurationException e) {
        throw new ProcessingException(e);
    } catch (ParsingException e) {
        throw new ProcessingException(e);
    }
    return samlResponse;
}
Also used : ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) SAML2Response(org.keycloak.saml.processing.api.saml.v2.response.SAML2Response) Document(org.w3c.dom.Document) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException)

Example 13 with ParsingException

use of org.keycloak.saml.common.exceptions.ParsingException in project keycloak by keycloak.

the class SAML2ErrorResponseBuilder method buildDocument.

public Document buildDocument() throws ProcessingException {
    try {
        StatusResponseType statusResponse = new ResponseType(IDGenerator.create("ID_"), XMLTimeUtil.getIssueInstant());
        statusResponse.setStatus(JBossSAMLAuthnResponseFactory.createStatusTypeForResponder(status));
        statusResponse.setIssuer(issuer);
        statusResponse.setDestination(destination);
        if (!this.extensions.isEmpty()) {
            ExtensionsType extensionsType = new ExtensionsType();
            for (NodeGenerator extension : this.extensions) {
                extensionsType.addExtension(extension);
            }
            statusResponse.setExtensions(extensionsType);
        }
        SAML2Response saml2Response = new SAML2Response();
        return saml2Response.convert(statusResponse);
    } catch (ConfigurationException e) {
        throw new ProcessingException(e);
    } catch (ParsingException e) {
        throw new ProcessingException(e);
    }
}
Also used : ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) ExtensionsType(org.keycloak.dom.saml.v2.protocol.ExtensionsType) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) SAML2Response(org.keycloak.saml.processing.api.saml.v2.response.SAML2Response) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException)

Example 14 with ParsingException

use of org.keycloak.saml.common.exceptions.ParsingException in project keycloak by keycloak.

the class KeycloakConfigurationServletListener method contextInitialized.

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext servletContext = sce.getServletContext();
    String configResolverClass = servletContext.getInitParameter("keycloak.config.resolver");
    SamlDeploymentContext deploymentContext = (SamlDeploymentContext) servletContext.getAttribute(SamlDeployment.class.getName());
    if (deploymentContext == null) {
        if (configResolverClass != null) {
            try {
                SamlConfigResolver configResolver = (SamlConfigResolver) servletContext.getClassLoader().loadClass(configResolverClass).newInstance();
                deploymentContext = new SamlDeploymentContext(configResolver);
                log.infov("Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass);
            } catch (Exception ex) {
                log.errorv("The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[] { configResolverClass, ex.getMessage() });
                deploymentContext = new SamlDeploymentContext(new DefaultSamlDeployment());
            }
        } else {
            InputStream is = getConfigInputStream(servletContext);
            final SamlDeployment deployment;
            if (is == null) {
                log.warn("No adapter configuration.  Keycloak is unconfigured and will deny all requests.");
                deployment = new DefaultSamlDeployment();
            } else {
                try {
                    ResourceLoader loader = new ResourceLoader() {

                        @Override
                        public InputStream getResourceAsStream(String resource) {
                            return servletContext.getResourceAsStream(resource);
                        }
                    };
                    deployment = new DeploymentBuilder().build(is, loader);
                } catch (ParsingException e) {
                    throw new RuntimeException(e);
                }
            }
            deploymentContext = new SamlDeploymentContext(deployment);
            log.debug("Keycloak is using a per-deployment configuration.");
        }
    }
    addTokenStoreUpdaters(servletContext);
    servletContext.setAttribute(ADAPTER_DEPLOYMENT_CONTEXT_ATTRIBUTE, deploymentContext);
    servletContext.setAttribute(ADAPTER_DEPLOYMENT_CONTEXT_ATTRIBUTE_ELYTRON, deploymentContext);
    servletContext.setAttribute(ADAPTER_SESSION_ID_MAPPER_ATTRIBUTE_ELYTRON, idMapper);
    servletContext.setAttribute(ADAPTER_SESSION_ID_MAPPER_UPDATER_ATTRIBUTE_ELYTRON, idMapperUpdater);
}
Also used : SamlDeploymentContext(org.keycloak.adapters.saml.SamlDeploymentContext) ResourceLoader(org.keycloak.adapters.saml.config.parsers.ResourceLoader) DefaultSamlDeployment(org.keycloak.adapters.saml.DefaultSamlDeployment) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) DefaultSamlDeployment(org.keycloak.adapters.saml.DefaultSamlDeployment) SamlDeployment(org.keycloak.adapters.saml.SamlDeployment) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) ServletContext(javax.servlet.ServletContext) SamlConfigResolver(org.keycloak.adapters.saml.SamlConfigResolver) DeploymentBuilder(org.keycloak.adapters.saml.config.parsers.DeploymentBuilder)

Example 15 with ParsingException

use of org.keycloak.saml.common.exceptions.ParsingException in project keycloak by keycloak.

the class SAMLIdentityProviderFactory method parseConfig.

@Override
public Map<String, String> parseConfig(KeycloakSession session, InputStream inputStream) {
    try {
        Object parsedObject = SAMLParser.getInstance().parse(inputStream);
        EntityDescriptorType entityType;
        if (EntitiesDescriptorType.class.isInstance(parsedObject)) {
            entityType = (EntityDescriptorType) ((EntitiesDescriptorType) parsedObject).getEntityDescriptor().get(0);
        } else {
            entityType = (EntityDescriptorType) parsedObject;
        }
        List<EntityDescriptorType.EDTChoiceType> choiceType = entityType.getChoiceType();
        if (!choiceType.isEmpty()) {
            IDPSSODescriptorType idpDescriptor = null;
            // So we need to loop through to find the IDPSSODescriptor.
            for (EntityDescriptorType.EDTChoiceType edtChoiceType : entityType.getChoiceType()) {
                List<EntityDescriptorType.EDTDescriptorChoiceType> descriptors = edtChoiceType.getDescriptors();
                if (!descriptors.isEmpty() && descriptors.get(0).getIdpDescriptor() != null) {
                    idpDescriptor = descriptors.get(0).getIdpDescriptor();
                }
            }
            if (idpDescriptor != null) {
                SAMLIdentityProviderConfig samlIdentityProviderConfig = new SAMLIdentityProviderConfig();
                String singleSignOnServiceUrl = null;
                boolean postBindingResponse = false;
                boolean postBindingLogout = false;
                for (EndpointType endpoint : idpDescriptor.getSingleSignOnService()) {
                    if (endpoint.getBinding().toString().equals(JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get())) {
                        singleSignOnServiceUrl = endpoint.getLocation().toString();
                        postBindingResponse = true;
                        break;
                    } else if (endpoint.getBinding().toString().equals(JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.get())) {
                        singleSignOnServiceUrl = endpoint.getLocation().toString();
                    }
                }
                String singleLogoutServiceUrl = null;
                for (EndpointType endpoint : idpDescriptor.getSingleLogoutService()) {
                    if (postBindingResponse && endpoint.getBinding().toString().equals(JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get())) {
                        singleLogoutServiceUrl = endpoint.getLocation().toString();
                        postBindingLogout = true;
                        break;
                    } else if (!postBindingResponse && endpoint.getBinding().toString().equals(JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.get())) {
                        singleLogoutServiceUrl = endpoint.getLocation().toString();
                        break;
                    }
                }
                samlIdentityProviderConfig.setSingleLogoutServiceUrl(singleLogoutServiceUrl);
                samlIdentityProviderConfig.setSingleSignOnServiceUrl(singleSignOnServiceUrl);
                samlIdentityProviderConfig.setWantAuthnRequestsSigned(idpDescriptor.isWantAuthnRequestsSigned());
                samlIdentityProviderConfig.setAddExtensionsElementWithKeyInfo(false);
                samlIdentityProviderConfig.setValidateSignature(idpDescriptor.isWantAuthnRequestsSigned());
                samlIdentityProviderConfig.setPostBindingResponse(postBindingResponse);
                samlIdentityProviderConfig.setPostBindingAuthnRequest(postBindingResponse);
                samlIdentityProviderConfig.setPostBindingLogout(postBindingLogout);
                samlIdentityProviderConfig.setLoginHint(false);
                List<String> nameIdFormatList = idpDescriptor.getNameIDFormat();
                if (nameIdFormatList != null && !nameIdFormatList.isEmpty())
                    samlIdentityProviderConfig.setNameIDPolicyFormat(nameIdFormatList.get(0));
                List<KeyDescriptorType> keyDescriptor = idpDescriptor.getKeyDescriptor();
                String defaultCertificate = null;
                if (keyDescriptor != null) {
                    for (KeyDescriptorType keyDescriptorType : keyDescriptor) {
                        Element keyInfo = keyDescriptorType.getKeyInfo();
                        Element x509KeyInfo = DocumentUtil.getChildElement(keyInfo, new QName("dsig", "X509Certificate"));
                        if (KeyTypes.SIGNING.equals(keyDescriptorType.getUse())) {
                            samlIdentityProviderConfig.addSigningCertificate(x509KeyInfo.getTextContent());
                        } else if (KeyTypes.ENCRYPTION.equals(keyDescriptorType.getUse())) {
                            samlIdentityProviderConfig.setEncryptionPublicKey(x509KeyInfo.getTextContent());
                        } else if (keyDescriptorType.getUse() == null) {
                            defaultCertificate = x509KeyInfo.getTextContent();
                        }
                    }
                }
                if (defaultCertificate != null) {
                    if (samlIdentityProviderConfig.getSigningCertificates().length == 0) {
                        samlIdentityProviderConfig.addSigningCertificate(defaultCertificate);
                    }
                    if (samlIdentityProviderConfig.getEncryptionPublicKey() == null) {
                        samlIdentityProviderConfig.setEncryptionPublicKey(defaultCertificate);
                    }
                }
                samlIdentityProviderConfig.setEnabledFromMetadata(entityType.getValidUntil() == null || entityType.getValidUntil().toGregorianCalendar().getTime().after(new Date(System.currentTimeMillis())));
                // check for hide on login attribute
                if (entityType.getExtensions() != null && entityType.getExtensions().getEntityAttributes() != null) {
                    for (AttributeType attribute : entityType.getExtensions().getEntityAttributes().getAttribute()) {
                        if (MACEDIR_ENTITY_CATEGORY.equals(attribute.getName()) && attribute.getAttributeValue().contains(REFEDS_HIDE_FROM_DISCOVERY)) {
                            samlIdentityProviderConfig.setHideOnLogin(true);
                        }
                    }
                }
                return samlIdentityProviderConfig.getConfig();
            }
        }
    } catch (ParsingException pe) {
        throw new RuntimeException("Could not parse IdP SAML Metadata", pe);
    }
    return new HashMap<>();
}
Also used : IDPSSODescriptorType(org.keycloak.dom.saml.v2.metadata.IDPSSODescriptorType) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) Element(org.w3c.dom.Element) Date(java.util.Date) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) EndpointType(org.keycloak.dom.saml.v2.metadata.EndpointType) EntityDescriptorType(org.keycloak.dom.saml.v2.metadata.EntityDescriptorType) KeyDescriptorType(org.keycloak.dom.saml.v2.metadata.KeyDescriptorType)

Aggregations

ParsingException (org.keycloak.saml.common.exceptions.ParsingException)31 ConfigurationException (org.keycloak.saml.common.exceptions.ConfigurationException)14 ProcessingException (org.keycloak.saml.common.exceptions.ProcessingException)14 InputStream (java.io.InputStream)11 Document (org.w3c.dom.Document)10 IOException (java.io.IOException)9 ByteArrayInputStream (java.io.ByteArrayInputStream)7 DeploymentBuilder (org.keycloak.adapters.saml.config.parsers.DeploymentBuilder)7 ResourceLoader (org.keycloak.adapters.saml.config.parsers.ResourceLoader)7 FileNotFoundException (java.io.FileNotFoundException)6 SamlDeployment (org.keycloak.adapters.saml.SamlDeployment)6 FileInputStream (java.io.FileInputStream)5 AuthnRequestType (org.keycloak.dom.saml.v2.protocol.AuthnRequestType)5 Test (org.junit.Test)4 DefaultSamlDeployment (org.keycloak.adapters.saml.DefaultSamlDeployment)4 SamlDeploymentContext (org.keycloak.adapters.saml.SamlDeploymentContext)4 SAML2Request (org.keycloak.saml.processing.api.saml.v2.request.SAML2Request)4 Element (org.w3c.dom.Element)4 HashMap (java.util.HashMap)3 ServletException (javax.servlet.ServletException)3