[BAEL-13600] - Updated HttpClient with SSL Header article
This commit is contained in:
+30
@@ -0,0 +1,30 @@
|
||||
package org.baeldung.basic;
|
||||
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
@Component
|
||||
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
|
||||
|
||||
@Override
|
||||
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
|
||||
response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
final PrintWriter writer = response.getWriter();
|
||||
writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
setRealmName("Baeldung");
|
||||
super.afterPropertiesSet();
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package org.baeldung.client;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.client.AuthCache;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.impl.auth.BasicScheme;
|
||||
import org.apache.http.impl.client.BasicAuthCache;
|
||||
import org.apache.http.protocol.BasicHttpContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
|
||||
public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory {
|
||||
|
||||
HttpHost host;
|
||||
|
||||
public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) {
|
||||
super();
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
|
||||
return createHttpContext();
|
||||
}
|
||||
|
||||
private HttpContext createHttpContext() {
|
||||
|
||||
AuthCache authCache = new BasicAuthCache();
|
||||
|
||||
BasicScheme basicAuth = new BasicScheme();
|
||||
authCache.put(host, basicAuth);
|
||||
|
||||
BasicHttpContext localcontext = new BasicHttpContext();
|
||||
localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
|
||||
return localcontext;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package org.baeldung.client;
|
||||
|
||||
import org.apache.http.HttpHost;
|
||||
import org.springframework.beans.factory.FactoryBean;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Component
|
||||
public class RestTemplateFactory implements FactoryBean<RestTemplate>, InitializingBean {
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
public RestTemplateFactory() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public RestTemplate getObject() {
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<RestTemplate> getObjectType() {
|
||||
return RestTemplate.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSingleton() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
HttpHost host = new HttpHost("localhost", 8082, "http");
|
||||
final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host);
|
||||
restTemplate = new RestTemplate(requestFactory);
|
||||
restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package org.baeldung.client.spring;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("org.baeldung.client")
|
||||
public class ClientConfig {
|
||||
|
||||
public ClientConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
// beans
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.baeldung.filter;
|
||||
|
||||
import org.springframework.web.filter.GenericFilterBean;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
public class CustomFilter extends GenericFilterBean {
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package org.baeldung.filter;
|
||||
|
||||
import org.baeldung.security.RestAuthenticationEntryPoint;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth
|
||||
.inMemoryAuthentication()
|
||||
.withUser("user1")
|
||||
.password(passwordEncoder().encode("user1Pass"))
|
||||
.authorities("ROLE_USER");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.antMatchers("/securityNone")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.httpBasic()
|
||||
.authenticationEntryPoint(authenticationEntryPoint);
|
||||
|
||||
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package org.baeldung.security;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
|
||||
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
|
||||
import org.springframework.security.web.savedrequest.RequestCache;
|
||||
import org.springframework.security.web.savedrequest.SavedRequest;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
|
||||
|
||||
private RequestCache requestCache = new HttpSessionRequestCache();
|
||||
|
||||
@Override
|
||||
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
|
||||
final SavedRequest savedRequest = requestCache.getRequest(request, response);
|
||||
|
||||
if (savedRequest == null) {
|
||||
super.onAuthenticationSuccess(request, response, authentication);
|
||||
|
||||
return;
|
||||
}
|
||||
final String targetUrlParameter = getTargetUrlParameter();
|
||||
if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
|
||||
requestCache.removeRequest(request, response);
|
||||
super.onAuthenticationSuccess(request, response, authentication);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
clearAuthenticationAttributes(request);
|
||||
|
||||
// Use the DefaultSavedRequest URL
|
||||
// final String targetUrl = savedRequest.getRedirectUrl();
|
||||
// logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
|
||||
// getRedirectStrategy().sendRedirect(request, response, targetUrl);
|
||||
}
|
||||
|
||||
public void setRequestCache(final RequestCache requestCache) {
|
||||
this.requestCache = requestCache;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package org.baeldung.security;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* The Entry Point will not redirect to any sort of Login - it will return the 401
|
||||
*/
|
||||
@Component
|
||||
public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
|
||||
@Override
|
||||
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
|
||||
@Configuration
|
||||
@ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
@ComponentScan("org.baeldung.security")
|
||||
public class SecSecurityConfig {
|
||||
|
||||
public SecSecurityConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan("org.baeldung.web")
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
public WebConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
// beans
|
||||
|
||||
@Override
|
||||
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
|
||||
converters.add(new MappingJackson2HttpMessageConverter());
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package org.baeldung.web.controller;
|
||||
|
||||
import org.baeldung.web.dto.Bar;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/bars")
|
||||
public class BarController {
|
||||
|
||||
@Autowired
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
public BarController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Bar findOne(@PathVariable("id") final Long id) {
|
||||
return new Bar();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package org.baeldung.web.controller;
|
||||
|
||||
import org.baeldung.web.dto.Foo;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/foos")
|
||||
public class FooController {
|
||||
|
||||
@Autowired
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
public FooController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
@PreAuthorize("hasRole('ROLE_USER')")
|
||||
public Foo findOne(@PathVariable("id") final Long id) {
|
||||
return new Foo();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.baeldung.web.dto;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
@XmlRootElement
|
||||
public class Bar implements Serializable {
|
||||
|
||||
public Bar() {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.baeldung.web.dto;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
@XmlRootElement
|
||||
public class Foo implements Serializable {
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/security
|
||||
http://www.springframework.org/schema/security/spring-security.xsd
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd"
|
||||
>
|
||||
|
||||
<http create-session="stateless" use-expressions="true">
|
||||
|
||||
<http-basic entry-point-ref="myBasicAuthenticationEntryPoint"/>
|
||||
|
||||
</http>
|
||||
|
||||
<authentication-manager>
|
||||
<authentication-provider>
|
||||
<user-service>
|
||||
<user name="user1" password="{noop}user1Pass" authorities="ROLE_USER"/>
|
||||
</user-service>
|
||||
</authentication-provider>
|
||||
</authentication-manager>
|
||||
|
||||
<global-method-security pre-post-annotations="enabled"/>
|
||||
|
||||
<beans:bean id="myBasicAuthenticationEntryPoint" class="org.baeldung.basic.MyBasicAuthenticationEntryPoint" />
|
||||
|
||||
</beans:beans>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
|
||||
>
|
||||
|
||||
<display-name>Spring Security Custom Application</display-name>
|
||||
|
||||
<!-- Spring root -->
|
||||
<context-param>
|
||||
<param-name>contextClass</param-name>
|
||||
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>org.baeldung.spring</param-value>
|
||||
</context-param>
|
||||
|
||||
<listener>
|
||||
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
|
||||
</listener>
|
||||
|
||||
<!-- Spring child -->
|
||||
<servlet>
|
||||
<servlet-name>api</servlet-name>
|
||||
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>api</servlet-name>
|
||||
<url-pattern>/api/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<!-- Spring Security -->
|
||||
<filter>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
|
||||
</filter>
|
||||
<filter-mapping>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
</web-app>
|
||||
@@ -0,0 +1,47 @@
|
||||
package org.baeldung.client;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.baeldung.client.spring.ClientConfig;
|
||||
import org.baeldung.web.dto.Foo;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { ClientConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class ClientLiveTest {
|
||||
|
||||
@Autowired
|
||||
private RestTemplate secureRestTemplate;
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenContextIsBootstrapped_thenNoExceptions() {
|
||||
//
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSecuredRestApiIsConsumed_then200OK() {
|
||||
final ResponseEntity<Foo> responseEntity = secureRestTemplate.exchange("http://localhost:8082/httpclient-simple/api/foos/1", HttpMethod.GET, null, Foo.class);
|
||||
assertThat(responseEntity.getStatusCode().value(), is(200));
|
||||
}
|
||||
|
||||
@Test(expected = ResourceAccessException.class)
|
||||
public final void whenHttpsUrlIsConsumed_thenException() {
|
||||
final String urlOverHttps = "https://localhost:8443/httpclient-simple/api/bars/1";
|
||||
final ResponseEntity<String> response = new RestTemplate().exchange(urlOverHttps, HttpMethod.GET, null, String.class);
|
||||
assertThat(response.getStatusCode().value(), equalTo(200));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package org.baeldung.client;
|
||||
|
||||
import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.config.Registry;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.SSLSocketFactory;
|
||||
import org.apache.http.conn.ssl.TrustStrategy;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
/**
|
||||
* This test requires a localhost server over HTTPS <br>
|
||||
* It should only be manually run, not part of the automated build
|
||||
* */
|
||||
public class RestClientLiveManualTest {
|
||||
|
||||
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
|
||||
|
||||
// tests
|
||||
|
||||
// old httpClient will throw UnsupportedOperationException
|
||||
@Ignore
|
||||
@Test
|
||||
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException_1() throws GeneralSecurityException {
|
||||
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
final CloseableHttpClient httpClient = (CloseableHttpClient) requestFactory.getHttpClient();
|
||||
|
||||
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
|
||||
@Override
|
||||
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER);
|
||||
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 8443, sf));
|
||||
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
|
||||
assertThat(response.getStatusCode().value(), equalTo(200));
|
||||
}
|
||||
|
||||
// new httpClient : 4.4 and above
|
||||
@Test
|
||||
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException_2() throws GeneralSecurityException {
|
||||
|
||||
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
|
||||
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
|
||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
|
||||
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
|
||||
.register("https", sslsf)
|
||||
.register("http", new PlainConnectionSocketFactory())
|
||||
.build();
|
||||
|
||||
final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
|
||||
final CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setSSLSocketFactory(sslsf)
|
||||
.setConnectionManager(connectionManager)
|
||||
.build();
|
||||
|
||||
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
|
||||
assertThat(response.getStatusCode().value(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAcceptingAllCertificatesUsing4_4_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException {
|
||||
final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
|
||||
|
||||
final HttpGet getMethod = new HttpGet(urlOverHttps);
|
||||
final HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAcceptingAllCertificatesUsing4_4_whenHttpsUrlIsConsumedUsingRestTemplate_thenCorrect() throws ClientProtocolException, IOException {
|
||||
final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
|
||||
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
requestFactory.setHttpClient(httpClient);
|
||||
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
|
||||
assertThat(response.getStatusCode().value(), equalTo(200));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package org.baeldung.httpclient;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.config.Registry;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
|
||||
import org.apache.http.conn.ssl.TrustStrategy;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.apache.http.ssl.SSLContextBuilder;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* This test requires a localhost server over HTTPS <br>
|
||||
* It should only be manually run, not part of the automated build
|
||||
* */
|
||||
public class HttpsClientSslLiveTest {
|
||||
|
||||
// "https://localhost:8443/spring-security-rest-basic-auth/api/bars/1" // local
|
||||
// "https://mms.nw.ru/" // hosted
|
||||
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
|
||||
|
||||
// tests
|
||||
|
||||
@Test(expected = SSLHandshakeException.class)
|
||||
public final void whenHttpsUrlIsConsumed_thenException() throws IOException {
|
||||
final CloseableHttpClient httpClient = HttpClientBuilder.create()
|
||||
.build();
|
||||
|
||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||
final HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
|
||||
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||
|
||||
final SSLContext sslContext = SSLContexts.custom()
|
||||
.loadTrustMaterial(null, acceptingTrustStrategy)
|
||||
.build();
|
||||
|
||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
|
||||
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
|
||||
PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
|
||||
|
||||
final CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setSSLSocketFactory(sslsf)
|
||||
.setConnectionManager(clientConnectionManager)
|
||||
.build();
|
||||
|
||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||
final HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
|
||||
httpClient.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
|
||||
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||
final SSLContext sslContext = SSLContexts.custom()
|
||||
.loadTrustMaterial(null, acceptingTrustStrategy)
|
||||
.build();
|
||||
|
||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
|
||||
|
||||
final CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setSSLSocketFactory(sslsf)
|
||||
.build();
|
||||
|
||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||
final HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
|
||||
httpClient.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
|
||||
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
|
||||
.build();
|
||||
final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
|
||||
|
||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
|
||||
final CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setSSLHostnameVerifier(hostnameVerifier)
|
||||
.setSSLSocketFactory(sslsf)
|
||||
.build();
|
||||
|
||||
// new
|
||||
|
||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||
final HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
httpClient.close();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
|
||||
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true)
|
||||
.build();
|
||||
|
||||
final CloseableHttpClient client = HttpClients.custom()
|
||||
.setSSLContext(sslContext)
|
||||
.setSSLHostnameVerifier(new NoopHostnameVerifier())
|
||||
.build();
|
||||
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
|
||||
httpGet.setHeader("Accept", "application/xml");
|
||||
|
||||
final HttpResponse response = client.execute(httpGet);
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package org.baeldung.test;
|
||||
|
||||
import org.baeldung.client.ClientLiveTest;
|
||||
import org.baeldung.client.RestClientLiveManualTest;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Suite;
|
||||
|
||||
@RunWith(Suite.class)
|
||||
@Suite.SuiteClasses({
|
||||
// @formatter:off
|
||||
RestClientLiveManualTest.class
|
||||
,ClientLiveTest.class
|
||||
}) //
|
||||
public class LiveTestSuite {
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user