Basic Authentication with Spring Security

In this article of REST with Spring,We will see how to build a basic authentication with Spring Security for REST API using Spring Boot.

Introduction

REST API‘s are becoming back bones of many modern enterprise applications. There are multiple choice for the RESTful Authentication. In this article we will build a basic authentication with Spring Security for REST API. Our secure REST API will ask for basic authentication before providing data access to the REST client.

1. Maven Setup

To secure our REST API, we need to include spring security starter in the pom.xml file.

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

This configuration will ensure following two points for our application:

  1. Provide REST API support (using Spring MVC)
  2. Spring security starters will serve the default security configuration for our application.

2. Spring Security Configuration

To enable the basic authentication for our REST API, let’s configure Spring Security by extending the WebSecurityConfigurerAdapter. This class provides a good base class for creating a WebSecurityConfigurer instance:

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable()
                .authorizeRequests().anyRequest().authenticated()
                .and().httpBasic();

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder authentication)
            throws Exception
    {
        authentication.inMemoryAuthentication()
                .withUser("admin")
                .password(passwordEncoder().encode("nimda"))
                .authorities("ROLE_USER");
    }

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

There are multiple things taking place in the above code. Let’s study details about the configure(HttpSecurity httpSecurity) method:

  1. Disable the CSRF feature.
  2. All requests to our application requires authentication.
  3. Allow users to use HTTP basic authentication.

In the configureGlobal(AuthenticationManagerBuilder authentication)method we are creating in memory user authentication details. With Spring Boot, we can always configure default user and password using the application.properties file (We can omit the configureGlobal(AuthenticationManagerBuilder authentication)method from above code). Use the following properties:

spring.security.user.name=#user name
spring.security.user.password=#password

3. Testing Basic Authentication

Our basic authentication with Spring for REST API is ready. To test our application, let’s build a simple REST controller:

3.1 REST Controller

@RestController
public class UserController {

    @GetMapping("/users")
    public User getUser(){
        return new User("Defaut User", "1", 40);
    }
}

This is a simple REST controller which returns user information back to the REST client.

3.1 REST Controller

Let’s try to call out REST API passing no authentication details:

Basic Authentication with Spring

When we tried to access our REST API using http://localhost:8080/users, it prompts for the basic username and password. On passing the correct credentials, we will have the user details back from our REST API:

Basic Authentication with Spring

Summary

In this article we learned how to enable the basic authentication with Spring using Spring Boot. We discussed how to use the Java configuration to enable this basic authentication using Spring Security. You can download the source code of this article from GitHub.