From fab2df5166fc6c974b0deeea3e282e0786586aa0 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 21 Apr 2019 00:19:55 +0530 Subject: [PATCH] [BAEL-13600] - Updated HttpClient with SSL Header article --- httpclient-simple/README.md | 3 +- httpclient-simple/pom.xml | 200 +++++++++++++++++- .../MyBasicAuthenticationEntryPoint.java | 30 +++ ...entsClientHttpRequestFactoryBasicAuth.java | 39 ++++ .../baeldung/client/RestTemplateFactory.java | 44 ++++ .../baeldung/client/spring/ClientConfig.java | 16 ++ .../org/baeldung/filter/CustomFilter.java | 18 ++ .../CustomWebSecurityConfigurerAdapter.java | 49 +++++ ...uestAwareAuthenticationSuccessHandler.java | 48 +++++ .../RestAuthenticationEntryPoint.java | 23 ++ .../baeldung/spring/SecSecurityConfig.java | 16 ++ .../java/org/baeldung/spring/WebConfig.java | 30 +++ .../web/controller/BarController.java | 31 +++ .../web/controller/FooController.java | 33 +++ .../main/java/org/baeldung/web/dto/Bar.java | 14 ++ .../main/java/org/baeldung/web/dto/Foo.java | 14 ++ .../src/main/resources/webSecurityConfig.xml | 28 +++ .../src/main/webapp/WEB-INF/api-servlet.xml | 6 + .../src/main/webapp/WEB-INF/web.xml | 43 ++++ .../org/baeldung/client/ClientLiveTest.java | 4 +- .../client/RestClientLiveManualTest.java | 38 +++- .../httpclient/HttpsClientSslLiveTest.java | 0 .../java/org/baeldung/test/LiveTestSuite.java | 0 spring-security-rest-basic-auth/README.md | 1 - spring-security-rest-basic-auth/pom.xml | 4 +- 25 files changed, 712 insertions(+), 20 deletions(-) create mode 100644 httpclient-simple/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/client/RestTemplateFactory.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/client/spring/ClientConfig.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/filter/CustomFilter.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/filter/CustomWebSecurityConfigurerAdapter.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/spring/SecSecurityConfig.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/spring/WebConfig.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/web/controller/BarController.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/web/controller/FooController.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/web/dto/Bar.java create mode 100644 httpclient-simple/src/main/java/org/baeldung/web/dto/Foo.java create mode 100644 httpclient-simple/src/main/resources/webSecurityConfig.xml create mode 100644 httpclient-simple/src/main/webapp/WEB-INF/api-servlet.xml create mode 100644 httpclient-simple/src/main/webapp/WEB-INF/web.xml rename {spring-security-rest-basic-auth => httpclient-simple}/src/test/java/org/baeldung/client/ClientLiveTest.java (88%) rename {spring-security-rest-basic-auth => httpclient-simple}/src/test/java/org/baeldung/client/RestClientLiveManualTest.java (63%) rename {httpclient => httpclient-simple}/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java (100%) rename {spring-security-rest-basic-auth => httpclient-simple}/src/test/java/org/baeldung/test/LiveTestSuite.java (100%) diff --git a/httpclient-simple/README.md b/httpclient-simple/README.md index aa66c11b1e..d1224359e0 100644 --- a/httpclient-simple/README.md +++ b/httpclient-simple/README.md @@ -7,4 +7,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [HttpClient 4 – Get the Status Code](http://www.baeldung.com/httpclient-status-code) \ No newline at end of file +- [HttpClient 4 – Get the Status Code](http://www.baeldung.com/httpclient-status-code) +- [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl) \ No newline at end of file diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index 1ad68d2804..f3d00251d7 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -5,15 +5,111 @@ httpclient-simple 0.1-SNAPSHOT httpclient-simple + war com.baeldung - parent-java + parent-spring-5 0.0.1-SNAPSHOT - ../parent-java + ../parent-spring-5 + + + + + org.springframework.security + spring-security-web + ${spring.version} + + + org.springframework.security + spring-security-config + ${spring.version} + + + + + + org.springframework + spring-core + ${spring.version} + + + commons-logging + commons-logging + + + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + + + org.springframework + spring-expression + ${spring.version} + + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + + org.springframework + spring-oxm + ${spring.version} + + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + + commons-logging + commons-logging + + + + org.apache.commons @@ -70,16 +166,77 @@ ${wiremock.version} test + + + + + javax.servlet + javax.servlet-api + ${javax.servlet.version} + provided + + + + javax.servlet + jstl + ${jstl.version} + runtime + + + + + + com.google.guava + guava + ${guava.version} + + + + + + org.springframework + spring-test + ${spring.version} + test + - httpclient + httpclient-simple src/main/resources true + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + @@ -87,6 +244,27 @@ live + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + org.apache.maven.plugins maven-surefire-plugin @@ -98,26 +276,28 @@ - **/*ManualTest.java + none **/*LiveTest.java + + cargo + - - - json - - + + + 1.2 + 3.1.0 19.0 3.5 @@ -125,8 +305,10 @@ 4.1.4 2.5.1 + 4.4.11 4.5.8 + 2.6 1.6.1 diff --git a/httpclient-simple/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/httpclient-simple/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java new file mode 100644 index 0000000000..6e580e7a22 --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -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(); + } + +} diff --git a/httpclient-simple/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/httpclient-simple/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java new file mode 100644 index 0000000000..a2f51d343b --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -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; + } +} \ No newline at end of file diff --git a/httpclient-simple/src/main/java/org/baeldung/client/RestTemplateFactory.java b/httpclient-simple/src/main/java/org/baeldung/client/RestTemplateFactory.java new file mode 100644 index 0000000000..3ed0bc82b7 --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/client/RestTemplateFactory.java @@ -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, InitializingBean { + private RestTemplate restTemplate; + + public RestTemplateFactory() { + super(); + } + + // API + + @Override + public RestTemplate getObject() { + return restTemplate; + } + + @Override + public Class 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")); + } + +} \ No newline at end of file diff --git a/httpclient-simple/src/main/java/org/baeldung/client/spring/ClientConfig.java b/httpclient-simple/src/main/java/org/baeldung/client/spring/ClientConfig.java new file mode 100644 index 0000000000..73e602855c --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/client/spring/ClientConfig.java @@ -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 + +} \ No newline at end of file diff --git a/httpclient-simple/src/main/java/org/baeldung/filter/CustomFilter.java b/httpclient-simple/src/main/java/org/baeldung/filter/CustomFilter.java new file mode 100644 index 0000000000..01e5b0b59d --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/filter/CustomFilter.java @@ -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); + } + +} diff --git a/httpclient-simple/src/main/java/org/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/httpclient-simple/src/main/java/org/baeldung/filter/CustomWebSecurityConfigurerAdapter.java new file mode 100644 index 0000000000..7ca2a80c52 --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/filter/CustomWebSecurityConfigurerAdapter.java @@ -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(); + } +} diff --git a/httpclient-simple/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/httpclient-simple/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java new file mode 100644 index 0000000000..698052fa2b --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -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; + } +} diff --git a/httpclient-simple/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java b/httpclient-simple/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java new file mode 100644 index 0000000000..77aa32ff97 --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java @@ -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"); + } + +} \ No newline at end of file diff --git a/httpclient-simple/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/httpclient-simple/src/main/java/org/baeldung/spring/SecSecurityConfig.java new file mode 100644 index 0000000000..4ce80dab9f --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -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(); + } + +} diff --git a/httpclient-simple/src/main/java/org/baeldung/spring/WebConfig.java b/httpclient-simple/src/main/java/org/baeldung/spring/WebConfig.java new file mode 100644 index 0000000000..5876e1307b --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/spring/WebConfig.java @@ -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> converters) { + converters.add(new MappingJackson2HttpMessageConverter()); + } + + // + +} \ No newline at end of file diff --git a/httpclient-simple/src/main/java/org/baeldung/web/controller/BarController.java b/httpclient-simple/src/main/java/org/baeldung/web/controller/BarController.java new file mode 100644 index 0000000000..2bc314baa2 --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/web/controller/BarController.java @@ -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(); + } + +} diff --git a/httpclient-simple/src/main/java/org/baeldung/web/controller/FooController.java b/httpclient-simple/src/main/java/org/baeldung/web/controller/FooController.java new file mode 100644 index 0000000000..b50edb2dcf --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/web/controller/FooController.java @@ -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(); + } + +} diff --git a/httpclient-simple/src/main/java/org/baeldung/web/dto/Bar.java b/httpclient-simple/src/main/java/org/baeldung/web/dto/Bar.java new file mode 100644 index 0000000000..d33e39a823 --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/web/dto/Bar.java @@ -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(); + } + +} diff --git a/httpclient-simple/src/main/java/org/baeldung/web/dto/Foo.java b/httpclient-simple/src/main/java/org/baeldung/web/dto/Foo.java new file mode 100644 index 0000000000..09c1dac933 --- /dev/null +++ b/httpclient-simple/src/main/java/org/baeldung/web/dto/Foo.java @@ -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(); + } + +} diff --git a/httpclient-simple/src/main/resources/webSecurityConfig.xml b/httpclient-simple/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..a93dc841b6 --- /dev/null +++ b/httpclient-simple/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/httpclient-simple/src/main/webapp/WEB-INF/api-servlet.xml b/httpclient-simple/src/main/webapp/WEB-INF/api-servlet.xml new file mode 100644 index 0000000000..1dbff70b83 --- /dev/null +++ b/httpclient-simple/src/main/webapp/WEB-INF/api-servlet.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/httpclient-simple/src/main/webapp/WEB-INF/web.xml b/httpclient-simple/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..83b4aeb0a7 --- /dev/null +++ b/httpclient-simple/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,43 @@ + + + + Spring Security Custom Application + + + + contextClass + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + contextConfigLocation + org.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + + + api + org.springframework.web.servlet.DispatcherServlet + 1 + + + api + /api/* + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + \ No newline at end of file diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java b/httpclient-simple/src/test/java/org/baeldung/client/ClientLiveTest.java similarity index 88% rename from spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java rename to httpclient-simple/src/test/java/org/baeldung/client/ClientLiveTest.java index 2a668f827a..286ee3c900 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java +++ b/httpclient-simple/src/test/java/org/baeldung/client/ClientLiveTest.java @@ -33,13 +33,13 @@ public class ClientLiveTest { @Test public final void whenSecuredRestApiIsConsumed_then200OK() { - final ResponseEntity responseEntity = secureRestTemplate.exchange("http://localhost:8082/spring-security-rest-basic-auth/api/foos/1", HttpMethod.GET, null, Foo.class); + final ResponseEntity 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/spring-security-rest-basic-auth/api/bars/1"; + final String urlOverHttps = "https://localhost:8443/httpclient-simple/api/bars/1"; final ResponseEntity response = new RestTemplate().exchange(urlOverHttps, HttpMethod.GET, null, String.class); assertThat(response.getStatusCode().value(), equalTo(200)); } diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java b/httpclient-simple/src/test/java/org/baeldung/client/RestClientLiveManualTest.java similarity index 63% rename from spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java rename to httpclient-simple/src/test/java/org/baeldung/client/RestClientLiveManualTest.java index 104129b663..53f259c21d 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java +++ b/httpclient-simple/src/test/java/org/baeldung/client/RestClientLiveManualTest.java @@ -8,19 +8,24 @@ import java.io.IOException; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLPeerUnverifiedException; +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.DefaultHttpClient; 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; @@ -34,14 +39,14 @@ import org.springframework.web.client.RestTemplate; * */ public class RestClientLiveManualTest { - final String urlOverHttps = "http://localhost:8082/spring-security-rest-basic-auth/api/bars/1"; + 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() throws GeneralSecurityException { + public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException_1() throws GeneralSecurityException { final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); final CloseableHttpClient httpClient = (CloseableHttpClient) requestFactory.getHttpClient(); @@ -57,6 +62,29 @@ public class RestClientLiveManualTest { final ResponseEntity 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 socketFactoryRegistry = RegistryBuilder. 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 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 { diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient-simple/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java similarity index 100% rename from httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java rename to httpclient-simple/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/test/LiveTestSuite.java b/httpclient-simple/src/test/java/org/baeldung/test/LiveTestSuite.java similarity index 100% rename from spring-security-rest-basic-auth/src/test/java/org/baeldung/test/LiveTestSuite.java rename to httpclient-simple/src/test/java/org/baeldung/test/LiveTestSuite.java diff --git a/spring-security-rest-basic-auth/README.md b/spring-security-rest-basic-auth/README.md index 30da3afbcf..0a48a747c2 100644 --- a/spring-security-rest-basic-auth/README.md +++ b/spring-security-rest-basic-auth/README.md @@ -8,6 +8,5 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Basic Authentication with the RestTemplate](http://www.baeldung.com/how-to-use-resttemplate-with-basic-authentication-in-spring) - [HttpClient Timeout](http://www.baeldung.com/httpclient-timeout) -- [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl) - [A Custom Filter in the Spring Security Filter Chain](http://www.baeldung.com/spring-security-custom-filter) - [Spring Security Basic Authentication](http://www.baeldung.com/spring-security-basic-authentication) diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index ca5c4c38e6..3c7f8eaa2b 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -272,8 +272,8 @@ - 4.4.5 - 4.5.3 + 4.4.11 + 4.5.8 1.2