1. Introduction

In this post, we will apply HTTP Basic authentication to Spring REST APIs. We will also see how to test secured controllers by mocking users to test cases.

You will learn

  • Configuring HTTP Basic authentication in Spring Boot 2 based applications.
  • Securing Spring based REST APIs.
  • Mocking user credentials in test cases of REST APIs.
  • Configuring stateless session for REST APIs.
  • Encode security passwords by using the build in class BCryptPasswordEncoder.

2. Dependencies

Let’s add the spring security and spring security test dependencies.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

3. Develop REST APIs

We will apply the spring security to the REST APIs we developed for ItemController in this post.

4. Securing Spring Controllers

Spring provides multiple methods to secure the spring controllers and methods. We will focus on HTTP Basic in this tutorial.

4.1. Default Security Provided by Spring Boot

When we include security dependency under Spring Boot 2 and not provide any security configuration, a form-based login is required to access controllers. Spring provides a user with name user and loads a random password while loading the application.

spring default security

Form-based login is good to access web-based resources. Let’s move to configure HTTP Basic security.

4.2. Configuring HTTP Basic Authentication

Let’s create a security configuration class by extending WebSecurityConfigurerAdapter class.

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

}

Now override configure method to enable HTTP Basic.

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

    http.csrf().disable();
    
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  
}

We have disabled CSRF check. REST APIs are stateless so we disabled session creation and usage.

Let’s create a user with a password.

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    auth.inMemoryAuthentication().withUser("user")
    .password("{noop}secret")
    .roles("USER");
}

We have used {noop} prefix before password. This prefix indicates that no password encoder used and it’s a plain text password.

Now launch the application and access REST APIs using configured credentials.

Postman REST API HTTP Basic Authentication POST Method

 

4.3. Configuring Password Encoder

Using a password encoder is a better approach then storing plain text passwords into an application. Let’s configure the application to use a build in password encoder service.

Create a new Bean for BCryptPasswordEncoder under Spring Boot Application.

@SpringBootApplication
public class RestApplication {

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }

    ....
}

Now edit the security configuration to use BCryptPasswordEncoder bean.

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
  
    ....

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user")
        .password(bCryptPasswordEncoder.encode("secret"))
        .roles("USER");
    }
}

4.4. Mock User with SpringBootTest

Now we need to provide credentials in our test cases. Let’s mock a user with all REST APIs test cases.

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ItemControllerTests {

    @WithMockUser(value = "user")
    @Test
    public void aSaveItems() throws Exception {
        ....
    }
}

We used @WithMockUser annotation with value user that is the actual username in security configuration. Spring tests automatically use the credentials for this user when sending requests to spring controllers.

Now try to run the spring tests and it would successfully test all REST APIs.

Spring Tests using HTTP Basic Authentication

That’s all!

2. Conclusion

In this post, we learned how to configure HTTP Basic authentication into Spring Boot 2 based REST APIs. We also saw some useful information for mocking users for Spring Boot test cases.

The complete source can be found over on GitHub.

Spring Boot 2 HTTP Basic Authentication

Satish Pandey

I am an expert Java Spring Angular developer with 10+ years of rich and varied experience in developing end-to-end Web Applications. I maintain this blog and publish articles in my free time to help the community. Email: satish@cloudtechpro.com

Leave a Reply

avatar
1024
  Subscribe  
Notify of