org.opensaml.saml.saml2.metadata.SPSSODescriptor Java Examples

The following examples show how to use org.opensaml.saml.saml2.metadata.SPSSODescriptor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UnsignedAssertionsResponseHandler.java    From verify-service-provider with MIT License 6 votes vote down vote up
public ValidatedResponse getValidatedResponse(
        List<Assertion> hubResponseAssertion,
        String expectedInResponseTo
) {
    ValidatedAssertions validatedHubAssertion = hubAssertionsSignatureValidator.validate(hubResponseAssertion, SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    ValidatedResponse validatedResponse = eidasValidatorFactory.getValidatedResponse(
            stringToResponseTransformer.apply(
                    getCountryResponseStringFromAssertion(validatedHubAssertion.getAssertions().get(ONLY_ONE_PRESENT))
            )
    );

    if (!expectedInResponseTo.equals(validatedResponse.getInResponseTo())) {
        throw new SamlResponseValidationException(
                String.format("Expected InResponseTo to be %s, but was %s", expectedInResponseTo, validatedResponse.getInResponseTo())
        );
    }

    instantValidator.validate(validatedResponse.getIssueInstant(), "Response IssueInstant");

    return validatedResponse;
}
 
Example #2
Source File: VerifyServiceProviderFactory.java    From verify-service-provider with MIT License 6 votes vote down vote up
public GenerateAuthnRequestResource getGenerateAuthnRequestResource() throws Exception {
    MetadataCredentialResolver metadataCredentialResolver = getHubMetadataCredentialResolver();
    MetadataBackedEncryptionCredentialResolver encryptionCredentialResolver = new MetadataBackedEncryptionCredentialResolver(metadataCredentialResolver, SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    EncrypterFactory encrypterFactory = new EncrypterFactory(encryptionCredentialResolver, configuration.getVerifyHubMetadata().getExpectedEntityId());

    PrivateKey signingKey = configuration.getSamlSigningKey();

    AuthnRequestFactory authnRequestFactory = new AuthnRequestFactory(
            configuration.getHubSsoLocation(),
            createKeyPair(signingKey),
            manifestReader, encrypterFactory
    );

    return new GenerateAuthnRequestResource(
        authnRequestFactory,
        configuration.getHubSsoLocation(),
        entityIdService
    );
}
 
Example #3
Source File: SamlMetadataUIParserAction.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Gets SP SSO descriptor.
 *
 * @param entityDescriptor the entity descriptor
 * @return the sPSSO descriptor
 */
private SPSSODescriptor getSPSSODescriptor(final EntityDescriptor entityDescriptor) {
    logger.debug("Locating SP SSO descriptor for SAML2 protocol...");
    SPSSODescriptor spssoDescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML20P_NS);
    if (spssoDescriptor == null) {
        logger.debug("Locating SP SSO descriptor for SAML11 protocol...");
        spssoDescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML11P_NS);
    }
    if (spssoDescriptor == null) {
        logger.debug("Locating SP SSO descriptor for SAML1 protocol...");
        spssoDescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML10P_NS);
    }
    logger.debug("SP SSO descriptor resolved to be [{}]", spssoDescriptor);
    return spssoDescriptor;
}
 
Example #4
Source File: ResponseService.java    From verify-service-provider with MIT License 5 votes vote down vote up
public TranslatedResponseBody convertTranslatedResponseBody(
    String decodedSamlResponse,
    String expectedInResponseTo,
    LevelOfAssurance expectedLevelOfAssurance,
    String entityId
) {
    Response response = samlObjectTransformer.apply(decodedSamlResponse);
    ValidatedResponse validatedResponse = responseSignatureValidator.validate(response, SPSSODescriptor.DEFAULT_ELEMENT_NAME);

    if (!expectedInResponseTo.equals(validatedResponse.getInResponseTo())) {
        throw new SamlResponseValidationException(
            String.format("Expected InResponseTo to be %s, but was %s", expectedInResponseTo, response.getInResponseTo())
        );
    }

    instantValidator.validate(validatedResponse.getIssueInstant(), "Response IssueInstant");

    StatusCode statusCode = validatedResponse.getStatus().getStatusCode();

    switch (statusCode.getValue()) {
        case StatusCode.RESPONDER:
            return responderCodeTranslator.translateResponderCode(statusCode);
        case StatusCode.SUCCESS:
            List<Assertion> assertions = assertionDecrypter.decryptAssertions(validatedResponse);
            if (assertionsContainEidasUnsignedAssertionsResponse(assertions)) {
                if (unsignedAssertionsResponseHandler == null) { throw new MissingUnsignedAssertionsHandlerException(); }

                ValidatedResponse validatedCountryResponse = unsignedAssertionsResponseHandler.getValidatedResponse(assertions, expectedInResponseTo);
                assertions = unsignedAssertionsResponseHandler.decryptAssertion(validatedCountryResponse, assertions.get(ONLY_ONE_PRESENT));
            }
            return assertionTranslator.translateSuccessResponse(assertions, expectedInResponseTo, expectedLevelOfAssurance, entityId);
        default:
            throw new SamlResponseValidationException(String.format("Unknown SAML status: %s", statusCode.getValue()));
    }
}
 
Example #5
Source File: UnsignedAssertionResponseHandlerTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void getValidatedResponseShouldValidateResponse() {
    List<Assertion> eidasSamlAssertion = Arrays.asList(anEidasSamlAssertion(singleKeyList));

    when(hubAssertionSignatureValidator.validate(eidasSamlAssertion, SPSSODescriptor.DEFAULT_ELEMENT_NAME)).thenReturn(new ValidatedAssertions(eidasSamlAssertion));
    when(stringToResponseTransformer.apply(samlString)).thenReturn(eidasResponse);
    when(eidasValidatorFactory.getValidatedResponse(eidasResponse)).thenReturn(validatedResponse);

    handler.getValidatedResponse(eidasSamlAssertion, inResponseTo);

    verify(hubAssertionSignatureValidator).validate(eidasSamlAssertion, SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    verify(stringToResponseTransformer).apply(samlString);
    verify(eidasValidatorFactory).getValidatedResponse(eidasResponse);
    verify(instantValidator).validate(validatedResponse.getIssueInstant(), "Response IssueInstant");
}
 
Example #6
Source File: UnsignedAssertionResponseHandlerTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void getValidatedResponseShouldThrowIfInResponseToIsNotExpected() {
    List<Assertion> eidasSamlAssertion = Arrays.asList(anEidasSamlAssertion(singleKeyList));

    when(hubAssertionSignatureValidator.validate(eidasSamlAssertion, SPSSODescriptor.DEFAULT_ELEMENT_NAME)).thenReturn(new ValidatedAssertions(eidasSamlAssertion));
    when(stringToResponseTransformer.apply(samlString)).thenReturn(eidasResponse);
    when(eidasValidatorFactory.getValidatedResponse(eidasResponse)).thenReturn(validatedResponse);

    assertThrows(SamlResponseValidationException.class, () -> {
        handler.getValidatedResponse(eidasSamlAssertion, "thisIsNotTheResponseIdYouAreLookingFor");
    });
}
 
Example #7
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRespondMetadataWithoutAuthentication() throws Exception {
    final AggregatedHttpResponse resp = client.get("/saml/metadata").aggregate().join();
    assertThat(resp.status()).isEqualTo(HttpStatus.OK);
    assertThat(resp.contentType()).isEqualTo(CONTENT_TYPE_SAML_METADATA);

    final EntityDescriptor metadata =
            (EntityDescriptor) deserialize(resp.contentUtf8().getBytes());
    assertThat(metadata).isNotNull();

    final SPSSODescriptor sp = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS);
    assertThat(sp.isAuthnRequestsSigned()).isTrue();
    assertThat(sp.getWantAssertionsSigned()).isTrue();

    final List<KeyDescriptor> kd = sp.getKeyDescriptors();
    assertThat(kd.get(0).getUse().name()).isEqualToIgnoringCase("signing");
    assertThat(kd.get(1).getUse().name()).isEqualToIgnoringCase("encryption");

    final List<SingleLogoutService> slo = sp.getSingleLogoutServices();
    assertThat(slo.get(0).getLocation())
            .isEqualTo("http://" + spHostname + ':' + rule.httpPort() + "/saml/slo/post");
    assertThat(slo.get(0).getBinding()).isEqualTo(SAMLConstants.SAML2_POST_BINDING_URI);
    assertThat(slo.get(1).getLocation())
            .isEqualTo("http://" + spHostname + ':' + rule.httpPort() + "/saml/slo/redirect");
    assertThat(slo.get(1).getBinding()).isEqualTo(SAMLConstants.SAML2_REDIRECT_BINDING_URI);

    final List<AssertionConsumerService> acs = sp.getAssertionConsumerServices();
    // index 0 (default)
    assertThat(acs.get(0).getIndex()).isEqualTo(0);
    assertThat(acs.get(0).isDefault()).isTrue();
    assertThat(acs.get(0).getLocation())
            .isEqualTo("http://" + spHostname + ':' + rule.httpPort() + "/saml/acs/post");
    assertThat(acs.get(0).getBinding()).isEqualTo(SAMLConstants.SAML2_POST_BINDING_URI);
    // index 1
    assertThat(acs.get(1).getIndex()).isEqualTo(1);
    assertThat(acs.get(1).isDefault()).isFalse();
    assertThat(acs.get(1).getLocation())
            .isEqualTo("http://" + spHostname + ':' + rule.httpPort() + "/saml/acs/redirect");
    assertThat(acs.get(1).getBinding()).isEqualTo(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
}
 
Example #8
Source File: SamlMetadataUIParserAction.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(requestContext);
    final String entityId = request.getParameter(this.entityIdParameterName);
    if (StringUtils.isBlank(entityId)) {
        logger.debug("No entity id found for parameter [{}]", this.entityIdParameterName);
        return success();
    }

    final WebApplicationService service = new SimpleWebApplicationServiceImpl(entityId);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        logger.debug("Entity id [{}] is not recognized/allowed by the CAS service registry", entityId);
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE,
                "Entity " + entityId + " not recognized");
    }

    final EntityDescriptor entityDescriptor = this.metadataAdapter.getEntityDescriptorForEntityId(entityId);
    if (entityDescriptor == null) {
        logger.debug("Entity descriptor not found for [{}]", entityId);
        return success();
    }

    final SPSSODescriptor spssoDescriptor = getSPSSODescriptor(entityDescriptor);
    if (spssoDescriptor == null) {
        logger.debug("SP SSO descriptor not found for [{}]", entityId);
        return success();
    }

    final Extensions extensions = spssoDescriptor.getExtensions();
    final List<XMLObject> spExtensions = extensions.getUnknownXMLObjects(UIInfo.DEFAULT_ELEMENT_NAME);
    if (spExtensions.isEmpty()) {
        logger.debug("No extensions are found for [{}]", UIInfo.DEFAULT_ELEMENT_NAME.getNamespaceURI());
        return success();
    }

    final SimpleMetadataUIInfo mdui = new SimpleMetadataUIInfo(registeredService);

    for (final XMLObject obj : spExtensions) {
        if (obj instanceof UIInfo) {
            final UIInfo uiInfo = (UIInfo) obj;
            logger.debug("Found UI info for [{}] and added to flow context", entityId);
            mdui.setUIInfo(uiInfo);
        }
    }

    requestContext.getFlowScope().put(MDUI_FLOW_PARAMETER_NAME, mdui);
    return success();
}
 
Example #9
Source File: SamlMetadataServiceFunction.java    From armeria with Apache License 2.0 4 votes vote down vote up
private EntityDescriptor buildMetadataEntityDescriptorElement(
        String defaultHostname, SamlPortConfig portConfig) {
    final EntityDescriptor entityDescriptor = build(EntityDescriptor.DEFAULT_ELEMENT_NAME);
    entityDescriptor.setEntityID(entityId);

    final SPSSODescriptor spSsoDescriptor = build(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    spSsoDescriptor.setAuthnRequestsSigned(true);
    spSsoDescriptor.setWantAssertionsSigned(true);
    spSsoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

    final List<String> nameIdFormats = idpConfigs.values().stream()
                                                 .map(p -> p.nameIdPolicy().format())
                                                 .distinct()
                                                 .map(SamlNameIdFormat::urn)
                                                 .collect(Collectors.toList());
    spSsoDescriptor.getNameIDFormats().addAll(buildNameIdFormatElements(nameIdFormats));

    final List<SingleLogoutService> sloList = spSsoDescriptor.getSingleLogoutServices();
    singleLogoutEndpoints.forEach(endpoint -> {
        final SingleLogoutService slo = build(SingleLogoutService.DEFAULT_ELEMENT_NAME);
        slo.setBinding(endpoint.bindingProtocol().urn());
        slo.setLocation(endpoint.toUriString(portConfig.scheme().uriText(),
                                             defaultHostname,
                                             portConfig.port()));
        sloList.add(slo);
    });

    int acsIndex = 0;
    final List<AssertionConsumerService> services = spSsoDescriptor.getAssertionConsumerServices();
    for (final SamlAssertionConsumerConfig acs : assertionConsumerConfigs) {
        services.add(buildAssertionConsumerServiceElement(acs, portConfig, defaultHostname, acsIndex++));
    }

    final X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
    keyInfoGeneratorFactory.setEmitEntityCertificate(true);
    keyInfoGeneratorFactory.setEmitEntityCertificateChain(true);
    final KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();

    try {
        spSsoDescriptor.getKeyDescriptors().add(
                buildKeyDescriptorElement(UsageType.SIGNING,
                                          keyInfoGenerator.generate(signingCredential)));
        spSsoDescriptor.getKeyDescriptors().add(
                buildKeyDescriptorElement(UsageType.ENCRYPTION,
                                          keyInfoGenerator.generate(encryptionCredential)));
    } catch (SecurityException e) {
        throw new SamlException("failed to generate KeyInfo element", e);
    }

    entityDescriptor.getRoleDescriptors().add(spSsoDescriptor);
    return entityDescriptor;
}
 
Example #10
Source File: ClientEntityDescriptor.java    From shibboleth-oidc with Apache License 2.0 4 votes vote down vote up
@Override
public SPSSODescriptor getSPSSODescriptor(final String supportedProtocol) {
    return null;
}
 
Example #11
Source File: SAML2SPLogic.java    From syncope with Apache License 2.0 4 votes vote down vote up
@PreAuthorize("isAuthenticated()")
public void getMetadata(final String spEntityID, final String urlContext, final OutputStream os) {
    check();

    try {
        EntityDescriptor spEntityDescriptor = new EntityDescriptorBuilder().buildObject();
        spEntityDescriptor.setEntityID(spEntityID);

        SPSSODescriptor spSSODescriptor = new SPSSODescriptorBuilder().buildObject();
        spSSODescriptor.setWantAssertionsSigned(true);
        spSSODescriptor.setAuthnRequestsSigned(true);
        spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
        keyInfoGeneratorFactory.setEmitEntityCertificate(true);
        KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();
        keyInfoGenerator.generate(loader.getCredential());

        KeyDescriptor keyDescriptor = new KeyDescriptorBuilder().buildObject();
        keyDescriptor.setKeyInfo(keyInfoGenerator.generate(loader.getCredential()));
        spSSODescriptor.getKeyDescriptors().add(keyDescriptor);

        NameIDFormat nameIDFormat = new NameIDFormatBuilder().buildObject();
        nameIDFormat.setFormat(NameIDType.PERSISTENT);
        spSSODescriptor.getNameIDFormats().add(nameIDFormat);
        nameIDFormat = new NameIDFormatBuilder().buildObject();
        nameIDFormat.setFormat(NameIDType.TRANSIENT);
        spSSODescriptor.getNameIDFormats().add(nameIDFormat);

        for (SAML2BindingType bindingType : SAML2BindingType.values()) {
            AssertionConsumerService assertionConsumerService = new AssertionConsumerServiceBuilder().buildObject();
            assertionConsumerService.setIndex(bindingType.ordinal());
            assertionConsumerService.setBinding(bindingType.getUri());
            assertionConsumerService.setLocation(getAssertionConsumerURL(spEntityID, urlContext));
            spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService);
            spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);

            String sloUrl = spEntityID + urlContext + "/logout";
            validateUrl(sloUrl);

            SingleLogoutService singleLogoutService = new SingleLogoutServiceBuilder().buildObject();
            singleLogoutService.setBinding(bindingType.getUri());
            singleLogoutService.setLocation(sloUrl);
            singleLogoutService.setResponseLocation(sloUrl);
            spSSODescriptor.getSingleLogoutServices().add(singleLogoutService);
        }

        spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);
        saml2rw.sign(spEntityDescriptor);

        SAML2ReaderWriter.write(new OutputStreamWriter(os), spEntityDescriptor, true);
    } catch (Exception e) {
        LOG.error("While getting SP metadata", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
}