[Spring boot + Spring Security] Handler Logout

1. Prepare Tools

  • IDE: Netbean 8.2
  • JDK: 1.8
  • Maven: 3.5.0

2. Target

Build project thỏa mãn các yêu cầu sau:

  • Sử dụng spring boot + spring security
    
  • Build controller handler logout
    
  • Sử dụng annotation configuration thay cho xml configuration.
    

3. Maven dependency

        <!-- Core starter, including auto-configuration support, logging and YAML -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- Starter for using Spring Security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

4. Project setup and description

1. Basic Project

https://viblo.asia/p/spring-boot-spring-security-basic-project-1VgZvEmpKAw

2. HttpSecurity

HttpSecurity của spring hỗ trợ builder xây dựng config cho logout http.logout() .logoutSuccessUrl("/login") .logoutUrl("/logout") .permitAll();

3. LogoutController

Xử lý logout đơn giản là việc loại bỏ object Authentication khỏi SecurityContextHolder của spring

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
    new SecurityContextLogoutHandler().logout(request, response, auth);
}

5. Demo

6. Full Source

spring-security-logout http://123link.vip/PvTjzI8