Search in sources :

Example 11 with EntityDescriptorType

use of org.keycloak.dom.saml.v2.metadata.EntityDescriptorType in project keycloak by keycloak.

the class IdentityProviderTest method assertSamlExport.

private void assertSamlExport(String body) throws ParsingException, URISyntaxException {
    // System.out.println(body);
    Object entBody = SAMLParser.getInstance().parse(new ByteArrayInputStream(body.getBytes(Charset.forName("utf-8"))));
    Assert.assertEquals("Parsed export type", EntityDescriptorType.class, entBody.getClass());
    EntityDescriptorType entity = (EntityDescriptorType) entBody;
    Assert.assertEquals("EntityID", oauth.AUTH_SERVER_ROOT + "/realms/admin-client-test", entity.getEntityID());
    Assert.assertNotNull("ChoiceType not null", entity.getChoiceType());
    Assert.assertEquals("ChoiceType.size", 1, entity.getChoiceType().size());
    List<EntityDescriptorType.EDTDescriptorChoiceType> descriptors = entity.getChoiceType().get(0).getDescriptors();
    Assert.assertNotNull("Descriptors not null", descriptors);
    Assert.assertEquals("Descriptors.size", 1, descriptors.size());
    SPSSODescriptorType desc = descriptors.get(0).getSpDescriptor();
    Assert.assertNotNull("SPSSODescriptor not null", desc);
    Assert.assertTrue("AuthnRequestsSigned", desc.isAuthnRequestsSigned());
    Set<String> expected = new HashSet<>(Arrays.asList("urn:oasis:names:tc:SAML:2.0:protocol"));
    Set<String> actual = new HashSet<>(desc.getProtocolSupportEnumeration());
    Assert.assertEquals("ProtocolSupportEnumeration", expected, actual);
    Assert.assertNotNull("AssertionConsumerService not null", desc.getAssertionConsumerService());
    Assert.assertEquals("AssertionConsumerService.size", 1, desc.getAssertionConsumerService().size());
    IndexedEndpointType endpoint = desc.getAssertionConsumerService().get(0);
    Assert.assertEquals("AssertionConsumerService.Location", new URI(oauth.AUTH_SERVER_ROOT + "/realms/admin-client-test/broker/saml/endpoint"), endpoint.getLocation());
    Assert.assertEquals("AssertionConsumerService.Binding", new URI("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"), endpoint.getBinding());
    Assert.assertTrue("AssertionConsumerService.isDefault", endpoint.isIsDefault());
    Assert.assertNotNull("SingleLogoutService not null", desc.getSingleLogoutService());
    Assert.assertEquals("SingleLogoutService.size", 1, desc.getSingleLogoutService().size());
    EndpointType sloEndpoint = desc.getSingleLogoutService().get(0);
    Assert.assertEquals("SingleLogoutService.Location", new URI(oauth.AUTH_SERVER_ROOT + "/realms/admin-client-test/broker/saml/endpoint"), sloEndpoint.getLocation());
    Assert.assertEquals("SingleLogoutService.Binding", new URI("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"), sloEndpoint.getBinding());
    Assert.assertNotNull("KeyDescriptor not null", desc.getKeyDescriptor());
    Assert.assertEquals("KeyDescriptor.size", 1, desc.getKeyDescriptor().size());
    KeyDescriptorType keyDesc = desc.getKeyDescriptor().get(0);
    assertThat(keyDesc, notNullValue());
    assertThat(keyDesc.getUse(), equalTo(KeyTypes.SIGNING));
    NodeList cert = keyDesc.getKeyInfo().getElementsByTagNameNS(XMLSignature.XMLNS, "X509Certificate");
    assertThat("KeyDescriptor.Signing.Cert existence", cert.getLength(), is(1));
}
Also used : NodeList(org.w3c.dom.NodeList) Matchers.containsString(org.hamcrest.Matchers.containsString) IndexedEndpointType(org.keycloak.dom.saml.v2.metadata.IndexedEndpointType) SPSSODescriptorType(org.keycloak.dom.saml.v2.metadata.SPSSODescriptorType) URI(java.net.URI) XMLDSIG_NSURI(org.keycloak.saml.common.constants.JBossSAMLURIConstants.XMLDSIG_NSURI) ByteArrayInputStream(java.io.ByteArrayInputStream) EndpointType(org.keycloak.dom.saml.v2.metadata.EndpointType) IndexedEndpointType(org.keycloak.dom.saml.v2.metadata.IndexedEndpointType) EntityDescriptorType(org.keycloak.dom.saml.v2.metadata.EntityDescriptorType) KeyDescriptorType(org.keycloak.dom.saml.v2.metadata.KeyDescriptorType) HashSet(java.util.HashSet)

Example 12 with EntityDescriptorType

use of org.keycloak.dom.saml.v2.metadata.EntityDescriptorType in project keycloak by keycloak.

the class SAMLMetadataWriter method writeEntityDescriptor.

public void writeEntityDescriptor(EntityDescriptorType entityDescriptor) throws ProcessingException {
    StaxUtil.writeStartElement(writer, METADATA_PREFIX, JBossSAMLConstants.ENTITY_DESCRIPTOR.get(), JBossSAMLURIConstants.METADATA_NSURI.get());
    StaxUtil.writeDefaultNameSpace(writer, JBossSAMLURIConstants.METADATA_NSURI.get());
    StaxUtil.writeNameSpace(writer, "md", JBossSAMLURIConstants.METADATA_NSURI.get());
    StaxUtil.writeNameSpace(writer, "saml", JBossSAMLURIConstants.ASSERTION_NSURI.get());
    StaxUtil.writeNameSpace(writer, "ds", JBossSAMLURIConstants.XMLDSIG_NSURI.get());
    StaxUtil.writeAttribute(writer, JBossSAMLConstants.ENTITY_ID.get(), entityDescriptor.getEntityID());
    if (entityDescriptor.getValidUntil() != null) {
        StaxUtil.writeAttribute(writer, JBossSAMLConstants.VALID_UNTIL.get(), entityDescriptor.getValidUntil().toString());
    }
    if (entityDescriptor.getID() != null) {
        StaxUtil.writeAttribute(writer, JBossSAMLConstants.ID.get(), entityDescriptor.getID());
    }
    Element signature = entityDescriptor.getSignature();
    if (signature != null) {
        StaxUtil.writeDOMElement(writer, signature);
    }
    ExtensionsType extensions = entityDescriptor.getExtensions();
    if (extensions != null) {
        write(extensions);
    }
    List<EntityDescriptorType.EDTChoiceType> choiceTypes = entityDescriptor.getChoiceType();
    for (EntityDescriptorType.EDTChoiceType edtChoice : choiceTypes) {
        AffiliationDescriptorType affliationDesc = edtChoice.getAffiliationDescriptor();
        if (affliationDesc != null)
            // TODO: affiliation
            throw logger.notImplementedYet("affliation");
        List<EntityDescriptorType.EDTDescriptorChoiceType> edtDescChoices = edtChoice.getDescriptors();
        for (EntityDescriptorType.EDTDescriptorChoiceType edtDescChoice : edtDescChoices) {
            RoleDescriptorType roleDesc = edtDescChoice.getRoleDescriptor();
            if (roleDesc != null)
                throw logger.notImplementedYet("Role Descriptor type");
            IDPSSODescriptorType idpSSO = edtDescChoice.getIdpDescriptor();
            if (idpSSO != null)
                write(idpSSO);
            SPSSODescriptorType spSSO = edtDescChoice.getSpDescriptor();
            if (spSSO != null)
                write(spSSO);
            AttributeAuthorityDescriptorType attribAuth = edtDescChoice.getAttribDescriptor();
            if (attribAuth != null)
                writeAttributeAuthorityDescriptor(attribAuth);
            AuthnAuthorityDescriptorType authNDesc = edtDescChoice.getAuthnDescriptor();
            if (authNDesc != null)
                throw logger.notImplementedYet("AuthnAuthorityDescriptorType");
            PDPDescriptorType pdpDesc = edtDescChoice.getPdpDescriptor();
            if (pdpDesc != null)
                throw logger.notImplementedYet("PDPDescriptorType");
        }
    }
    OrganizationType organization = entityDescriptor.getOrganization();
    if (organization != null) {
        writeOrganization(organization);
    }
    List<ContactType> contactPersons = entityDescriptor.getContactPerson();
    for (ContactType contact : contactPersons) {
        write(contact);
    }
    List<AdditionalMetadataLocationType> addl = entityDescriptor.getAdditionalMetadataLocation();
    if (addl.size() > 0)
        throw logger.notImplementedYet("AdditionalMetadataLocationType");
    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
Also used : AuthnAuthorityDescriptorType(org.keycloak.dom.saml.v2.metadata.AuthnAuthorityDescriptorType) IDPSSODescriptorType(org.keycloak.dom.saml.v2.metadata.IDPSSODescriptorType) ContactType(org.keycloak.dom.saml.v2.metadata.ContactType) Element(org.w3c.dom.Element) AffiliationDescriptorType(org.keycloak.dom.saml.v2.metadata.AffiliationDescriptorType) OrganizationType(org.keycloak.dom.saml.v2.metadata.OrganizationType) SPSSODescriptorType(org.keycloak.dom.saml.v2.metadata.SPSSODescriptorType) RoleDescriptorType(org.keycloak.dom.saml.v2.metadata.RoleDescriptorType) PDPDescriptorType(org.keycloak.dom.saml.v2.metadata.PDPDescriptorType) ExtensionsType(org.keycloak.dom.saml.v2.metadata.ExtensionsType) AttributeAuthorityDescriptorType(org.keycloak.dom.saml.v2.metadata.AttributeAuthorityDescriptorType) AdditionalMetadataLocationType(org.keycloak.dom.saml.v2.metadata.AdditionalMetadataLocationType) EntityDescriptorType(org.keycloak.dom.saml.v2.metadata.EntityDescriptorType)

Example 13 with EntityDescriptorType

use of org.keycloak.dom.saml.v2.metadata.EntityDescriptorType 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)

Example 14 with EntityDescriptorType

use of org.keycloak.dom.saml.v2.metadata.EntityDescriptorType in project keycloak by keycloak.

the class UserAttributeMapper method updateMetadata.

// SamlMetadataDescriptorUpdater interface
@Override
public void updateMetadata(IdentityProviderMapperModel mapperModel, EntityDescriptorType entityDescriptor) {
    String attributeName = mapperModel.getConfig().get(UserAttributeMapper.ATTRIBUTE_NAME);
    String attributeFriendlyName = mapperModel.getConfig().get(UserAttributeMapper.ATTRIBUTE_FRIENDLY_NAME);
    RequestedAttributeType requestedAttribute = new RequestedAttributeType(attributeName);
    requestedAttribute.setIsRequired(null);
    requestedAttribute.setNameFormat(ATTRIBUTE_FORMAT_BASIC.get());
    if (attributeFriendlyName != null && attributeFriendlyName.length() > 0)
        requestedAttribute.setFriendlyName(attributeFriendlyName);
    // Add the requestedAttribute item to any AttributeConsumingServices
    for (EntityDescriptorType.EDTChoiceType choiceType : entityDescriptor.getChoiceType()) {
        List<EntityDescriptorType.EDTDescriptorChoiceType> descriptors = choiceType.getDescriptors();
        for (EntityDescriptorType.EDTDescriptorChoiceType descriptor : descriptors) {
            for (AttributeConsumingServiceType attributeConsumingService : descriptor.getSpDescriptor().getAttributeConsumingService()) {
                boolean alreadyPresent = attributeConsumingService.getRequestedAttribute().stream().anyMatch(t -> (attributeName == null || attributeName.equalsIgnoreCase(t.getName())) && (attributeFriendlyName == null || attributeFriendlyName.equalsIgnoreCase(t.getFriendlyName())));
                if (!alreadyPresent)
                    attributeConsumingService.addRequestedAttribute(requestedAttribute);
            }
        }
    }
}
Also used : EntityDescriptorType(org.keycloak.dom.saml.v2.metadata.EntityDescriptorType) AttributeConsumingServiceType(org.keycloak.dom.saml.v2.metadata.AttributeConsumingServiceType) RequestedAttributeType(org.keycloak.dom.saml.v2.metadata.RequestedAttributeType)

Example 15 with EntityDescriptorType

use of org.keycloak.dom.saml.v2.metadata.EntityDescriptorType in project keycloak by keycloak.

the class AttributeToRoleMapper method updateMetadata.

// SamlMetadataDescriptorUpdater interface
@Override
public void updateMetadata(IdentityProviderMapperModel mapperModel, EntityDescriptorType entityDescriptor) {
    String attributeName = mapperModel.getConfig().get(UserAttributeMapper.ATTRIBUTE_NAME);
    String attributeFriendlyName = mapperModel.getConfig().get(AttributeToRoleMapper.ATTRIBUTE_FRIENDLY_NAME);
    RequestedAttributeType requestedAttribute = new RequestedAttributeType(mapperModel.getConfig().get(AttributeToRoleMapper.ATTRIBUTE_NAME));
    requestedAttribute.setIsRequired(null);
    requestedAttribute.setNameFormat(ATTRIBUTE_FORMAT_BASIC.get());
    if (attributeFriendlyName != null && attributeFriendlyName.length() > 0)
        requestedAttribute.setFriendlyName(attributeFriendlyName);
    // Add the requestedAttribute item to any AttributeConsumingServices
    for (EntityDescriptorType.EDTChoiceType choiceType : entityDescriptor.getChoiceType()) {
        List<EntityDescriptorType.EDTDescriptorChoiceType> descriptors = choiceType.getDescriptors();
        for (EntityDescriptorType.EDTDescriptorChoiceType descriptor : descriptors) {
            for (AttributeConsumingServiceType attributeConsumingService : descriptor.getSpDescriptor().getAttributeConsumingService()) {
                boolean alreadyPresent = attributeConsumingService.getRequestedAttribute().stream().anyMatch(t -> (attributeName == null || attributeName.equalsIgnoreCase(t.getName())) && (attributeFriendlyName == null || attributeFriendlyName.equalsIgnoreCase(t.getFriendlyName())));
                if (!alreadyPresent)
                    attributeConsumingService.addRequestedAttribute(requestedAttribute);
            }
        }
    }
}
Also used : EntityDescriptorType(org.keycloak.dom.saml.v2.metadata.EntityDescriptorType) AttributeConsumingServiceType(org.keycloak.dom.saml.v2.metadata.AttributeConsumingServiceType) RequestedAttributeType(org.keycloak.dom.saml.v2.metadata.RequestedAttributeType)

Aggregations

EntityDescriptorType (org.keycloak.dom.saml.v2.metadata.EntityDescriptorType)23 SPSSODescriptorType (org.keycloak.dom.saml.v2.metadata.SPSSODescriptorType)10 Test (org.junit.Test)9 EndpointType (org.keycloak.dom.saml.v2.metadata.EndpointType)9 KeyDescriptorType (org.keycloak.dom.saml.v2.metadata.KeyDescriptorType)9 IndexedEndpointType (org.keycloak.dom.saml.v2.metadata.IndexedEndpointType)7 Element (org.w3c.dom.Element)7 SAMLParser (org.keycloak.saml.processing.core.parsers.saml.SAMLParser)6 StringInputStream (org.apache.tools.ant.filters.StringInputStream)5 IDPSSODescriptorType (org.keycloak.dom.saml.v2.metadata.IDPSSODescriptorType)5 RequestedAttributeType (org.keycloak.dom.saml.v2.metadata.RequestedAttributeType)5 Closeable (java.io.Closeable)4 QName (javax.xml.namespace.QName)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 AttributeConsumingServiceType (org.keycloak.dom.saml.v2.metadata.AttributeConsumingServiceType)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 StringWriter (java.io.StringWriter)3 URI (java.net.URI)3 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)3 AttributeType (org.keycloak.dom.saml.v2.assertion.AttributeType)3