Search in sources :

Example 61 with UriComponentsBuilder

use of org.springframework.web.util.UriComponentsBuilder in project dhis2-core by dhis2.

the class CorsFilter method isOriginWhitelisted.

private boolean isOriginWhitelisted(HttpServletRequest request, String origin) {
    HttpServletRequestEncodingWrapper encodingWrapper = new HttpServletRequestEncodingWrapper(request);
    UriComponentsBuilder uriBuilder = ServletUriComponentsBuilder.fromContextPath(encodingWrapper).replacePath("");
    String forwardedProto = request.getHeader("X-Forwarded-Proto");
    if (!StringUtils.isEmpty(forwardedProto)) {
        uriBuilder.scheme(forwardedProto);
    }
    String localUrl = uriBuilder.build().toString();
    return !StringUtils.isEmpty(origin) && (localUrl.equals(origin) || configurationService.isCorsWhitelisted(origin));
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ServletUriComponentsBuilder(org.springframework.web.servlet.support.ServletUriComponentsBuilder)

Example 62 with UriComponentsBuilder

use of org.springframework.web.util.UriComponentsBuilder in project midpoint by Evolveum.

the class OidcClientModuleWebSecurityConfiguration method buildInternal.

private static OidcClientModuleWebSecurityConfiguration buildInternal(OidcAuthenticationModuleType modelType, String prefixOfSequence, String publicHttpUrlPattern, ServletRequest request) {
    OidcClientModuleWebSecurityConfiguration configuration = new OidcClientModuleWebSecurityConfiguration();
    build(configuration, modelType, prefixOfSequence);
    List<OidcClientAuthenticationModuleType> clients = modelType.getClient();
    List<ClientRegistration> registrations = new ArrayList<>();
    clients.forEach(client -> {
        OidcOpenIdProviderType openIdProvider = client.getOpenIdProvider();
        Assert.notNull(openIdProvider, "openIdProvider cannot be null");
        ClientRegistration.Builder builder = null;
        try {
            builder = ClientRegistrations.fromOidcIssuerLocation(openIdProvider.getIssuerUri());
        } catch (Exception e) {
            LOGGER.debug("Couldn't create oidc client builder by issuer uri.");
        }
        Assert.hasText(client.getRegistrationId(), "registrationId cannot be empty");
        if (builder == null) {
            builder = ClientRegistration.withRegistrationId(client.getRegistrationId());
        } else {
            builder.registrationId(client.getRegistrationId());
        }
        builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
        builder.userInfoAuthenticationMethod(AuthenticationMethod.HEADER);
        UriComponentsBuilder redirectUri = UriComponentsBuilder.fromUriString(StringUtils.isNotBlank(publicHttpUrlPattern) ? publicHttpUrlPattern : getBasePath((HttpServletRequest) request));
        redirectUri.pathSegment(DEFAULT_PREFIX_OF_MODULE, AuthUtil.stripSlashes(prefixOfSequence), AuthUtil.stripSlashes(modelType.getName()), AuthUtil.stripSlashes(RemoteModuleAuthenticationImpl.AUTHENTICATION_REQUEST_PROCESSING_URL_SUFFIX), client.getRegistrationId());
        builder.redirectUri(redirectUri.toUriString());
        Assert.hasText(client.getClientId(), "clientId cannot be empty");
        builder.clientId(client.getClientId());
        if (client.getNameOfUsernameAttribute() != null) {
            builder.userNameAttributeName(client.getNameOfUsernameAttribute());
        }
        if (!Objects.isNull(client.getClientSecret())) {
            try {
                String clientSecret = protector.decryptString(client.getClientSecret());
                builder.clientSecret(clientSecret);
            } catch (EncryptionException e) {
                LOGGER.error("Couldn't obtain clear string for client secret");
            }
        }
        getOptionalIfNotEmpty(client.getClientName()).ifPresent(builder::clientName);
        getOptionalIfNotEmpty(openIdProvider.getAuthorizationUri()).ifPresent(builder::authorizationUri);
        getOptionalIfNotEmpty(openIdProvider.getTokenUri()).ifPresent(builder::tokenUri);
        getOptionalIfNotEmpty(openIdProvider.getUserInfoUri()).ifPresent(builder::userInfoUri);
        getOptionalIfNotEmpty(openIdProvider.getIssuerUri()).ifPresent(builder::issuerUri);
        ClientRegistration clientRegistration = builder.build();
        if (clientRegistration.getScopes() == null || !clientRegistration.getScopes().contains("openid")) {
            List<String> scopes = new ArrayList<>();
            if (clientRegistration.getScopes() != null) {
                scopes.addAll(clientRegistration.getScopes());
            }
            scopes.add("openid");
            builder.scope(scopes);
        }
        if (StringUtils.isNotEmpty(openIdProvider.getEndSessionUri())) {
            Map<String, Object> configurationMetadata = new HashMap<>(clientRegistration.getProviderDetails().getConfigurationMetadata());
            configurationMetadata.remove("end_session_endpoint");
            configurationMetadata.put("end_session_endpoint", openIdProvider.getEndSessionUri());
            builder.providerConfigurationMetadata(configurationMetadata);
        }
        if (client.getClientAuthenticationMethod() != null) {
            builder.clientAuthenticationMethod(new ClientAuthenticationMethod(client.getClientAuthenticationMethod().name().toLowerCase()));
        }
        clientRegistration = builder.build();
        Assert.hasText(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri(), "UserInfoUri cannot be empty");
        registrations.add(clientRegistration);
        OidcAdditionalConfiguration.Builder additionalConfBuilder = OidcAdditionalConfiguration.builder().singingAlg(client.getClientSigningAlgorithm());
        if (client.getSimpleProofKey() != null) {
            initializeProofKey(client.getSimpleProofKey(), additionalConfBuilder);
        } else if (client.getKeyStoreProofKey() != null) {
            initializeProofKey(client.getKeyStoreProofKey(), additionalConfBuilder);
        }
        configuration.additionalConfiguration.put(client.getRegistrationId(), additionalConfBuilder.build());
    });
    configuration.clientRegistrationRepository = new InMemoryClientRegistrationRepository(registrations);
    return configuration;
}
Also used : InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Base64Exception(org.apache.cxf.common.util.Base64Exception) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException)

Example 63 with UriComponentsBuilder

use of org.springframework.web.util.UriComponentsBuilder in project midpoint by Evolveum.

the class SamlModuleWebSecurityConfiguration method createRelyingPartyRegistration.

private static void createRelyingPartyRegistration(RelyingPartyRegistration.Builder registrationBuilder, SamlAdditionalConfiguration.Builder additionalConfigBuilder, Saml2ProviderAuthenticationModuleType providerType, String publicHttpUrlPattern, SamlModuleWebSecurityConfiguration configuration, Saml2KeyAuthenticationModuleType keysType, Saml2ServiceProviderAuthenticationModuleType serviceProviderType, ServletRequest request) {
    String linkText = providerType.getLinkText() == null ? providerType.getEntityId() : providerType.getLinkText();
    additionalConfigBuilder.nameOfUsernameAttribute(providerType.getNameOfUsernameAttribute()).linkText(linkText);
    String registrationId = StringUtils.isNotEmpty(serviceProviderType.getAliasForPath()) ? serviceProviderType.getAliasForPath() : (StringUtils.isNotEmpty(serviceProviderType.getAlias()) ? serviceProviderType.getAlias() : serviceProviderType.getEntityId());
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(StringUtils.isNotBlank(publicHttpUrlPattern) ? publicHttpUrlPattern : getBasePath((HttpServletRequest) request));
    UriComponentsBuilder ssoBuilder = builder.cloneBuilder();
    ssoBuilder.pathSegment(AuthUtil.stripSlashes(configuration.getPrefixOfModule()) + SSO_LOCATION_URL_SUFFIX);
    UriComponentsBuilder logoutBuilder = builder.cloneBuilder();
    logoutBuilder.pathSegment(AuthUtil.stripSlashes(configuration.getPrefixOfModule()) + LOGOUT_LOCATION_URL_SUFFIX);
    registrationBuilder.registrationId(registrationId).entityId(serviceProviderType.getEntityId()).assertionConsumerServiceLocation(ssoBuilder.build().toUriString()).singleLogoutServiceLocation(logoutBuilder.build().toUriString()).assertingPartyDetails(party -> {
        party.entityId(providerType.getEntityId());
        if (serviceProviderType.isSignRequests() != null) {
            party.wantAuthnRequestsSigned(Boolean.TRUE.equals(serviceProviderType.isSignRequests()));
        }
        if (providerType.getVerificationKeys() != null && !providerType.getVerificationKeys().isEmpty()) {
            party.verificationX509Credentials(c -> providerType.getVerificationKeys().forEach(verKey -> {
                byte[] certbytes = new byte[0];
                try {
                    certbytes = protector.decryptString(verKey).getBytes();
                } catch (EncryptionException e) {
                    LOGGER.error("Couldn't obtain clear string for provider verification key");
                }
                try {
                    X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(certbytes));
                    c.add(new Saml2X509Credential(certificate, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION));
                } catch (CertificateException e) {
                    LOGGER.error("Couldn't obtain certificate from " + verKey);
                }
            }));
        }
    });
    Saml2X509Credential activeCredential = null;
    ModuleSaml2SimpleKeyType simpleKeyType = keysType.getActiveSimpleKey();
    if (simpleKeyType != null) {
        activeCredential = getSaml2Credential(simpleKeyType, true);
    }
    ModuleSaml2KeyStoreKeyType storeKeyType = keysType.getActiveKeyStoreKey();
    if (storeKeyType != null) {
        activeCredential = getSaml2Credential(storeKeyType, true);
    }
    List<Saml2X509Credential> credentials = new ArrayList<>();
    if (activeCredential != null) {
        credentials.add(activeCredential);
    }
    if (keysType.getStandBySimpleKey() != null && !keysType.getStandBySimpleKey().isEmpty()) {
        for (ModuleSaml2SimpleKeyType standByKey : keysType.getStandBySimpleKey()) {
            Saml2X509Credential credential = getSaml2Credential(standByKey, false);
            if (credential != null) {
                credentials.add(credential);
            }
        }
    }
    if (keysType.getStandByKeyStoreKey() != null && !keysType.getStandByKeyStoreKey().isEmpty()) {
        for (ModuleSaml2KeyStoreKeyType standByKey : keysType.getStandByKeyStoreKey()) {
            Saml2X509Credential credential = getSaml2Credential(standByKey, false);
            if (credential != null) {
                credentials.add(credential);
            }
        }
    }
    if (!credentials.isEmpty()) {
        registrationBuilder.decryptionX509Credentials(c -> credentials.forEach(cred -> {
            if (cred.getCredentialTypes().contains(Saml2X509Credential.Saml2X509CredentialType.DECRYPTION)) {
                c.add(cred);
            }
        }));
        registrationBuilder.signingX509Credentials(c -> credentials.forEach(cred -> {
            if (cred.getCredentialTypes().contains(Saml2X509Credential.Saml2X509CredentialType.SIGNING)) {
                c.add(cred);
            }
        }));
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) CertificateFactory(java.security.cert.CertificateFactory) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) InMemoryRelyingPartyRegistrationRepository(org.springframework.security.saml2.provider.service.registration.InMemoryRelyingPartyRegistrationRepository) HashMap(java.util.HashMap) Trace(com.evolveum.midpoint.util.logging.Trace) StringUtils(org.apache.commons.lang3.StringUtils) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) ArrayList(java.util.ArrayList) AuthUtil(com.evolveum.midpoint.authentication.api.util.AuthUtil) HttpServletRequest(javax.servlet.http.HttpServletRequest) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) Map(java.util.Map) PKCSException(org.bouncycastle.pkcs.PKCSException) java.security(java.security) ServletRequest(javax.servlet.ServletRequest) MidpointAssertingPartyMetadataConverter(com.evolveum.midpoint.authentication.impl.saml.MidpointAssertingPartyMetadataConverter) AuthSequenceUtil.getBasePath(com.evolveum.midpoint.authentication.impl.util.AuthSequenceUtil.getBasePath) ResourceLoader(org.springframework.core.io.ResourceLoader) Files(java.nio.file.Files) Saml2Exception(org.springframework.security.saml2.Saml2Exception) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) CertificateException(java.security.cert.CertificateException) List(java.util.List) Certificate(java.security.cert.Certificate) java.io(java.io) Paths(java.nio.file.Paths) Protector(com.evolveum.midpoint.prism.crypto.Protector) Base64Exception(org.apache.cxf.common.util.Base64Exception) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate)

Example 64 with UriComponentsBuilder

use of org.springframework.web.util.UriComponentsBuilder in project midpoint by Evolveum.

the class OidcClientLogoutSuccessHandler method endpointUri.

private String endpointUri(URI endSessionEndpoint, String idToken, String postLogoutRedirectUri) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUri(endSessionEndpoint);
    builder.queryParam("id_token_hint", idToken);
    if (postLogoutRedirectUri != null) {
        builder.queryParam("post_logout_redirect_uri", postLogoutRedirectUri);
    }
    return builder.encode(StandardCharsets.UTF_8).build().toUriString();
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder)

Example 65 with UriComponentsBuilder

use of org.springframework.web.util.UriComponentsBuilder in project ontrack by nemerosa.

the class DefaultURIBuilder method build.

@Override
public URI build(Object methodInvocation) {
    // Default builder
    UriComponentsBuilder builder = MvcUriComponentsBuilder.fromMethodCall(methodInvocation);
    // Default URI
    UriComponents uriComponents = builder.build();
    // TODO #251 Workaround for SPR-12771
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
    HttpRequest httpRequest = new ServletServerHttpRequest(request);
    String portHeader = httpRequest.getHeaders().getFirst("X-Forwarded-Port");
    if (StringUtils.hasText(portHeader)) {
        int port = Integer.parseInt(portHeader);
        String scheme = uriComponents.getScheme();
        if (("https".equals(scheme) && port == 443) || ("http".equals(scheme) && port == 80)) {
            port = -1;
        }
        builder.port(port);
    }
    // OK
    return builder.build().toUri();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpRequest(org.springframework.http.HttpRequest) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) UriComponents(org.springframework.web.util.UriComponents) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ServletUriComponentsBuilder(org.springframework.web.servlet.support.ServletUriComponentsBuilder) MvcUriComponentsBuilder(org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) RequestAttributes(org.springframework.web.context.request.RequestAttributes)

Aggregations

UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)131 Test (org.junit.Test)34 UriComponents (org.springframework.web.util.UriComponents)23 ServletUriComponentsBuilder (org.springframework.web.servlet.support.ServletUriComponentsBuilder)12 URI (java.net.URI)9 Test (org.junit.jupiter.api.Test)9 SearchRequest (org.nzbhydra.searching.searchrequests.SearchRequest)8 MvcUriComponentsBuilder (org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder)8 ArrayList (java.util.ArrayList)7 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)7 List (java.util.List)6 User (com.serotonin.m2m2.vo.User)5 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)5 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)5 HashMap (java.util.HashMap)5 HttpEntity (org.springframework.http.HttpEntity)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)5 IOException (java.io.IOException)4 Map (java.util.Map)4