Securing REST Webservice using Spring Security

This blog post is about applying authentication to a REST web service. The REST in context is consumed by various mobile application and a web application.

We will be using Spring Security as our Security Framework. In order to understand this blog post it is recommended that you should drill through the basics of Spring security.There are numerous tutorials on web for this.

So lets start securing our REST web service.

Step 1 –  Apply Spring Security’s DelegatingFilterProxy to the URLs that you want to secure.

org.springframework.web.filter.DelegatingFilterProxy is a servlet filter that brings spring security into work, it intercepts the requests to the URL that we are trying to secure. It further interacts with other Spring Security Filter each designated with its own task.

In the web.xml of project add below entries :-

<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>

Once these entries are there in your web.xml each request coming to your context will go through spring security.

Step 2 –  Configure Spring Security 

Import a beans configuration file that will hold all the security related beans and configurations. Configure an authentication manager.

Step 3 – Create a class that will serve as the entry point for our authentication.

We need to create a class that will extend Spring’s AuthenticationEntryPoint class and override its method commence. This method will reject every unauthenticated request and send error code 401

@Component(value=”restAuthenticationEntryPoint”)
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

public void commence(HttpServletRequest arg0, HttpServletResponse response,            AuthenticationException arg2) throws IOException, ServletException

{

response.sendError(HttpServletResponse.SC_UNAUTHORIZED, “Unauthorized”);

}}

Step 4 – Configure Spring security to use above entry point.

<http use-expressions=”true”

entry-point-ref=”restAuthenticationEntryPoint”>

<intercept-url pattern=”/*” access=”isAuthenticated()” />
<sec:form-login

authentication-success-handler -ref=”restSuccessHandler”

authentication-failure-handler-ref=”restAuthenticationFailureHandler” />

<logout />  </http>

Step 5 – Create a Login success handler that we declared in the above entry.

This success handler will write  response that will contain message for successful a authentication and session identifier, as server cannot write session id cookie on mobile devices as it does on browser.

@Component(value=”restSuccessHandler”)

public class RestLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {

String sessionId=request.getSession().getId();
// Please write response containing this session id

}

}

Step 6 – Create a Login failure handler that we declared in the above entry.

This failure handler will write the failure message

@Component(value=”restAuthenticationFailureHandler”)

public class RestLoginFailureHandler extends SimpleUrlAuthenticationFailureHandler{

@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {

// TODO Write response containing failure message

}

}

Step 7 – Add a exception translator and connect it with our authentication entry point.

<beans:bean id=”exceptionTranslationFilter”
class=”org.springframework.security.web.access.ExceptionTranslationFilter”>

<beans:property name=”restAuthenticationEntryPoint” ref=”restAuthenticationEntryPoint” />

</beans:bean>

Step 8 –  Test the login by sending a post request to the below url

[Your application url]/j_spring_security_check?j_username=[Username]&j_password=[

Step 9 – Test the Logout by sending a request to below URL
http://localhost:8080/webservice/j_spring_security_logout

Step 10 – Consuming it on mobile

Hit the login url, Retrieve the session ID, and add it the request headers of every request.

You can post any query/issues related to this blog, we at Paxcel technology will be happy to help you.

References :  Spring Security 3 by Peter Mularien.

3 thoughts on “Securing REST Webservice using Spring Security

  1. Hi, i have one problem with your solution. I always get the message:
    Authentication method not supported: GET
    And i dont know what to do….

    Thanks for any help
    Axel

Leave a Reply

Your email address will not be published. Required fields are marked *


8 + six =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>