Securing Restful web services using Spring-Security

After several months of silent, I woke up… With some security interests!
The security is a common requirement on many web projects, and fortunately, Spring helps us to implement it.
The most common way to do it is just defining a set of rules and letting Spring manage the login and so on.
In this demo, I will use Spring-boot (for its simplicity) but the security configuration is exactly the same with a web application.
And to be clear, I do not have the pretentiousness that this is THE way to follow when you need to secure your web services and I am convinced that someone else found another way to do it, but this is my solution, I used it several times, and it works perfectly, so maybe it will help someone else… One day 🙂

To start simply, I just built a simple web site with 2 pages:

  • the home page (/index.html), which is freely accessible
  • and another page (/secured/page.html) which is in a restricted area

Using Spring-boot, the structure is something like:

structure

By default, Spring boot published everything under the static directory and is accessible via http://localhost:8080/

For instance, everybody can access to our pages, it’s time to remedy to that state.

Let’s start with the interesting part of the Maven Configuration:

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>1.3.2.RELEASE</version>
	<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<java.version>1.8</java.version>
</properties>

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-security</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>

The starter dependencies are somehow facilitators provided by Spring boot to add some dependencies, I think that we can guess their purpose just by their name. For more information about this pom, you can have a look to the Spring-boot site.

Now, we have to restrict access to the secured part of the site, this is done here:

@Configuration
@EnableWebSecurity
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().
          withUser("admin").password("password").roles("ADMIN", "USER").and().
          withUser("user").password("password").roles("USER");
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception { 
        http
        .authorizeRequests()
        .antMatchers(HttpMethod.GET, "/secured/**").access("hasRole('USER')");
        
        //indicate that we are user login form authentication
        http.formLogin();
    }
}

For the demo, I define my users directly in the application, this is AuthenticationManagerBuilder.inMemoryAuthentication().

Inside the configure(HttpSecurity http) method, you can see that I just defined the URL of the secured part, indicating who can access it based on role.
And finally, I indicate that I want to use the form login authentication as it is provided by Spring.

According to the configuration, the users can access freely the home page, but only the users authenticated and with the right role can access to the secured part. This is a perfect configuration for a standard web site, but remember that we nee to secure a web service, the redirection to a login form is not an acceptable way for that purpose and we need to customise this behavior.

The first issue to solve is to avoid to redirection to the login form in case of unauthenticated access, I do it by changing the AuthenticationEntryPoint with mine:

@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
			throws IOException, ServletException {
		response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
	}
}

As you can see, this is very simple, I just need to send the right HTTP code to inform my client that it needs to authenticate before accessing the resource it requested.
And to indicate to Spring that I slightly changed the authentication, it is very complicated because… Well, it’s Spring, so, I just need to add the following in my SecurityJavaConfig:

[...]
@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
[...]
protected void configure(HttpSecurity http) throws Exception {
	http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
}

Now, when someone… As we are dealing with web services,I should say something tries to access to secured resources, it just receives an unauthorized HTTP code instead of a redirection to the login page.
That’s a good point but we have also to manage the successful and erroneous authentication. Instead of redirecting to a page, we have to inform the client that the credentials are valid or not .
For each case, we need to define two different classes:

  • in case of success, we let Spring clean-up the temporary data:
    @Component
    public class RestAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    	@Override
    	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
    			Authentication authentication) throws IOException, ServletException {
    		clearAuthenticationAttributes(request);
    	}
    }
    
  • in case of error, we return an HTTP code and an optional message:
    @Component
    public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler{
    	@Override
    	public void onAuthenticationFailure(HttpServletRequest arg0, HttpServletResponse arg1, AuthenticationException arg2)
    			throws IOException, ServletException {
    		arg1.sendError(HttpServletResponse.SC_FORBIDDEN, "Wrong username or password");
    	}
    }
    
  • And then the last step is to add them to the Spring configuration:

    [...]
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    [...]
    protected void configure(HttpSecurity http) throws Exception {
    	[...]
    	FormLoginConfigurer formLogin = http.formLogin();
    	[...]
    	formLogin.successHandler(authenticationSuccessHandler);
    	formLogin.failureHandler(authenticationFailureHandler);
    
    }
    

    Now, we can define our web services, and Spring will manage authentication for us.
    To protect your services, obviously, you need to add something like:

    http
    .authorizeRequests()
    [...]
    .antMatchers(HttpMethod.GET, "/secured/services/**")
    .access("hasRole('SERVICE_USER')");
    

    And you can also restrict access by the HTTP methods, someone can read data (GET method) but could not be allowed to modify it (POST/PUT methods).
    That’s it!

    In a next post, I will show how I used it with Angular-js, stay tuned 😀

    (the full project is available on Github)

Leave a comment