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));
}
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;
}
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);
}
}));
}
}
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();
}
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();
}
Aggregations