Close

Spring Boot - Security Custom Configuration

[Updated: Jun 3, 2018, Created: Jun 3, 2018]

To replace the default web application security configuration, we need to add a bean of type WebSecurityConfigurerAdapter.

Example

In the this example we are going to add multiple users. We will also add logout functionality.

Configuration

@SpringBootApplication
public class SpringBootSecurityExampleMain {

  @Bean
  public WebSecurityConfigurerAdapter webSecurityConfig() {
      return new WebSecurityConfigurerAdapter() {
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              http.authorizeRequests()
                  .anyRequest().authenticated()
                  .and()
                  .formLogin();
          }

          @Override
          protected void configure(AuthenticationManagerBuilder builder) throws Exception {
              BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
              builder.inMemoryAuthentication().passwordEncoder(passwordEncoder)
                     .withUser("joe").password(passwordEncoder.encode("123")).roles("USER")
                     .and()
                     .withUser("sara").password(passwordEncoder.encode("234")).roles("ADMIN")
              ;
          }
      };
  }

  public static void main(String[] args) {
      SpringApplication.run(SpringBootSecurityExampleMain.class);
  }
}

Controller

@Controller
public class AppController {

  @RequestMapping("/**")
  public String handler(ModelMap model, HttpServletRequest request) {
      Authentication auth = SecurityContextHolder.getContext()
                                                 .getAuthentication();
      model.addAttribute("uri", request.getRequestURI());
      model.addAttribute("user", auth.getName());
      model.addAttribute("roles", auth.getAuthorities());
      return "app";
  }
}

Thymeleaf View

src/main/resources/templates/app.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<body>
 <h2>Spring Secured App</h2>
 <p>app content ......... at uri <span th:text="${uri}"/></p>
 <p>User: <span th:text="${user}"/></p>
 <p>Roles: <span th:text="${roles}"/></p>
 <br/>
  <form action="/logout" method="post">
    <input type="hidden"
           th:name="${_csrf.parameterName}"
           th:value="${_csrf.token}"/>
    <input type="submit" value="Logout">
  </form>
</body>
</html>

Running application

To try examples, run spring-boot maven plugin (configured in pom.xml of example project below):

mvn spring-boot:run

Or run the main method class from IDE.

Output

Accessing page at localhost:8080/

Entering valid user name/password and submitting the form:

Logging out:

Using configuration class with @EnableWebSecurity

Instead of using bean of type WebSecurityConfigurerAdapter, we can also create a separate class with the same configuration:

package com.logicbig.example;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        builder.inMemoryAuthentication().passwordEncoder(passwordEncoder)
               .withUser("joe").password(passwordEncoder.encode("123")).roles("USER")
               .and()
               .withUser("sara").password(passwordEncoder.encode("234")).roles("ADMIN")
        ;
    }
}

Example Project

Dependencies and Technologies Used:

  • Spring Boot 2.0.2.RELEASE
    Corresponding Spring Version 5.0.6.RELEASE
  • spring-boot-starter-security : Starter for using Spring Security.
    Uses org.springframework.security:spring-security-web version 5.0.5.RELEASE
  • spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • spring-boot-starter-thymeleaf : Starter for building MVC web applications using Thymeleaf views.
    Uses org.thymeleaf:thymeleaf-spring5 version 3.0.9.RELEASE
  • JDK 1.8
  • Maven 3.3.9

Security Custom Configuration Select All Download
  • boot-security-customization
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • templates

See Also