Search code examples
web-servicesspring-mvcspring-securityspring-bootrestful-authentication

Secure Restful Spring boot application


I have developed a RESTful web service using Spring Boot. Once a URL is entered, a JSON resource is returned. The server side is not perfectly JSON API conformed but it works.

Now I want to secure the RESTful service with simple HTTP basic authentication. Simply put, if a client send a HTTP GET in order to access

http://mycompany.com/restful/xyz

it will receive a HTTP unauthenticated error, unless the request is configured with proper Authorization basic XXXXXXXX. The xxxxxx is the encrypted form of user:pwd

I wanted to do it with Spring Security. After some googling I might need to create some class like:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
     ....
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      ....
    }
}

There are two things I need to understand:

  1. Most Spring Security sample I found were somehow related to web application using Spring MVC, but I am sure that it can be used in a scenario as shown above - a standalone web service (in a Tomcat all right, but not a web app);

  2. Can anyone show some code snippet in the two methods above that work to the effect that only certain user/pwd is allowed to pass the filter to the resource,

    http://mycompany.com/restful/xyz
    

    otherwise a HTTP authentication error code is returned.

Can anyone help?


Solution

  • You can have something like this:

    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/restful/**").hasRole("ROLE_USER").and().httpBasic();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("john").password("mypass").roles("ROLE_USER");
        }
    }