Sponsors
components — such as the Spring MVC DispatcherServlet and the managed ap-
plication web-controllers. This is done in the web application descriptor file lo-
cated in /WEB-INF/web.xml, by configuring a filter of type DelegatingFilterProxy
with name springSecurityFilterChain. The filter mapping is set to match (at least)
the set of URLs we want to secure.
< f i l t e r>
< f i l t e r −name> s p r i n g S e c u r i t y F i l t e r C h a i n</ f i l t e r −name>
< f i l t e r −c l a s s>org . spr ingfr amewo rk . web . f i l t e r .
D e l e g a t i n g F i l t e r P r o x y</ f i l t e r −c l a s s>
</ f i l t e r>
< f i l t e r −mapping>
< f i l t e r −name> s p r i n g S e c u r i t y F i l t e r C h a i n</ f i l t e r −name>
<url−pattern>/ se c u r ed</ url−pattern>
</ f i l t e r −mapping>
3 Building a Client for Secured Rest Web Ser-
vices
This section shows how to implementing a Java client of secured REST-WS.
The Spring Framework class RestTemplate is configured appropriately to support
HTTP Basic authentication. The solution is specific to Java clients using Spring
Framework, but porting to other client environments is also feasible.
Spring RestTemplate API provides methods that roughly correspond to the
HTTP methods sent in a request. For example, to obtain a remote resource
using an HTTP GET request we use RestTemplate.getForObject(). RestTemplate
automatically perform marsalling and unmarshalling of Java objects and HTTP
responses.
Since Spring Security was configured in your sample REST-WS to require
HTTP Basic authentication, we need to tailor the behavior of RestTemplate
so that the appropriate HTTP authentication headers are set. Fortunately,
RestTemplate has extension point that allow for this. The strategy interface
ClientHttpRequestFactory is used by RestTemplate to create the actual connection
to the HTTP server. Two implementations are provided out-of-the-box: one im-
plementation that wraps the java.net.HttpConnection class, this is SimpleClientHttpRequestFactory
; and another that wraps the third-party open-source Apache HttpClient class.
Because BASIC authentication is simple enough, I will start by using Java java
.net.HttpConnection and SimpleClientHttpRequestFactory.
3.1 Invoking the Secure REST Web-Service
Below, I show the code for a simple REST-WS client that invokes a secured
method. This is done by class RestClient. A Spring RestTemplate is defined as
a data-field for the RestClient class, configured in the constructor. The configura-
tion is done by setting a custom ClientHttpRequestFactory of type BasicSecureSimpleClientHttpRequestFactory
though a call to the property setter method RestTemplate.setRequestFactory.
package org . he l l o a p p . r e s t s e c u r i t y . c l i e n t ;
4