Fancy UI

All About Crazy IT Stuff

Secure REST services using Spring Security

with 5 comments

Overview :

Recently, I was working on a project which uses a REST services layer to communicate with the client application (GWT application). So I have spent a lot of to time to figure out how to secure the REST services with Spring Security. This article describe the solution I found, and I have implemented. I hope that this solution will be helpful to someone and will save a much valuable time.

The solution :

In a normal web application, whenever a secured resource is accessed Spring Security check the security context for the current user and will decide either to forward him to login page (if the user is not authenticated), or to forward him to the resource not authorised page (if he doesn’t have the required permissions).

In our scenario this is different, because we don’t have pages to forward to, we need to adapt and override Spring Security to communicate using HTTP protocols status only, below I liste the things to do to make Spring Security works best :

  • The authentication is going to be managed by the normal form login, the only difference is that the response will be on JSON along with an HTTP status which can either code 200 (if the autentication passed) or code 401 (if the authentication failed) ;
  • Override the AuthenticationFailureHandler to return the code 401 UNAUTHORIZED ;
  • Override the AuthenticationSuccessHandler to return the code 20 OK, the body of the HTTP response contain the JSON data of the current authenticated user ;
  • Override the AuthenticationEntryPoint to always return the code 401 UNAUTHORIZED. This will override the default behavior of Spring Security which is forwarding the user to the login page if he don’t meet the security requirements, because on REST we don’t have any login page ;
  • Override the LogoutSuccessHandler to return the code 20 OK ;

Like a normal web application secured by Spring Security, before accessing a protected service, it is mandatory to first authenticate by submitting the password and username to the Login URL.

Note: The following solution requires Spring Security in version minimum 3.2.

Overriding the AuthenticationEntryPoint :

Class extends, and implements only one method, which sends response error (with 401 status code) in cause of unauthorized attempt.

public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint {
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());

Overriding the AuthenticationSuccessHandler :

The AuthenticationSuccessHandler is responsible of what to do after a successful authentication, by default it will redirect to an URL, but in our case we want it to send an HTTP response with data.

public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class);

    private final ObjectMapper mapper;

    AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) {
        this.mapper = messageConverter.getObjectMapper();

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

        NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal();
        User user = userDetails.getUser();
        userDetails.setUser(user); + " got is connected ");

        PrintWriter writer = response.getWriter();
        mapper.writeValue(writer, user);

Overriding the AuthenticationFailureHandler :

The AuthenticationFaillureHandler is responsible of what to after a failed authentication, by default it will redirect to the login page URL, but in our case we just want it to send an HTTP response with the 401 UNAUTHORIZED code.

public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {

        PrintWriter writer = response.getWriter();

Overriding the LogoutSuccessHandler :

The LogoutSuccessHandler decide what to do if the user logged out successfully, by default it will redirect to the login page URL, because we don’t have that I did override it to return an HTTP response with the 20 OK code.

public class HttpLogoutSuccessHandler implements LogoutSuccessHandler {
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {

Spring security configuration :

This is the final step, to put all what we did together, I prefer using the new way to configure Spring Security which is with Java no XML, but you can easily adapt this configuration to XML.

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private static final String LOGIN_PATH = ApiPaths.ROOT + ApiPaths.User.ROOT + ApiPaths.User.LOGIN;

    private NuvolaUserDetailsService userDetailsService;
    private HttpAuthenticationEntryPoint authenticationEntryPoint;
    private AuthSuccessHandler authSuccessHandler;
    private AuthFailureHandler authFailureHandler;
    private HttpLogoutSuccessHandler logoutSuccessHandler;

    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();

    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();

    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setPasswordEncoder(new ShaPasswordEncoder());

        return authenticationProvider;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();

    protected void configure(HttpSecurity http) throws Exception {
                .logoutRequestMatcher(new AntPathRequestMatcher(LOGIN_PATH, "DELETE"))


This was a sneak peak at the overall configuration, I attached in this article a Github repository containing a sample project

I hope this will help some of you developers struggling to figure out a solution, please feel free to ask any questions, or post any enhancements that can make this solution better.

Written by imrabti

August 29, 2014 at 8:24 am

Posted in GWT, REST, Spring

Tagged with , , ,

5 Responses

Subscribe to comments with RSS.

  1. how can i use this with requestfactory


    September 1, 2014 at 3:06 pm

    • RequestFactory uses HTTP protocol also invocation and JSON (but the protocole is not based upon REST).
      I think the project can be adapted a bit to use Requestfactory instead (Are you using RequestFactory with Spring services layer ?).


      September 1, 2014 at 3:36 pm

  2. Hi, Can you throw some light on Login processing URL?
    I do not have Spring MVC in my project, how can I use your code?


    August 3, 2015 at 10:39 am

    • In this project I use a spring MVC as REST services provider, the login processing is the same one provided by spring security.


      December 23, 2015 at 11:51 am

  3. Thanks for the post. Was really helpfull!

    Daan Smits

    March 13, 2016 at 8:43 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: