Spring Security Logout – Spring 安全框架退出登录

最后修改: 2022年 11月 11日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This article is building on top of our Form Login tutorial and is going to focus on the how to configure Logout with Spring Security.

本文是在我们的Form Login 教程的基础上编写的,将重点介绍如何使用Spring Security配置Logout

2. Basic Configuration

2.基本配置

The basic configuration of Spring Logout functionality using the logout() method is simple enough:

使用logout()方法对Spring注销功能的基本配置非常简单。

@Configuration
@EnableWebSecurity
public class SecSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
          //...
          .logout()
          //...
   }
   //...
}

And using XML configuration:

并使用XML配置。

<http>

    ...    
    <logout/>

</http>

The element enables the default logout mechanism – which is configured to use the following logout url: /logout which used to be /j_spring_security_logout before Spring Security 4.

该元素启用了默认的注销机制–它被配置为使用以下注销url/logout,在Spring Security 4之前是/j_spring_security_logout。。

3. The JSP and the Logout Link

3.JSP和注销链接

Continuing this simple example, the way to provide a logout link in the web application is:

继续这个简单的例子,在网络应用中提供一个logout链接的方法是。

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
   <head></head>
   <body>
      <a href="<c:url value="/logout" />">Logout</a>
   </body>
</html>

4. Advanced Customizations

4.高级定制

4.1. logoutSuccessUrl()

4.1.logoutSuccessUrl()

After the logout process is performed successfully, Spring Security will redirect the user to a specified page. By default, this is the root page (“/”) but this is configurable:

在成功执行注销过程后,Spring Security将把用户重定向到一个指定的页面。默认情况下,这是根页面(“/”),但这是可配置的。

//...
.logout()
.logoutSuccessUrl("/afterlogout.html")
//...

This can also be done using XML configuration:

这也可以用XML配置来完成。

<logout logout-success-url="/afterlogout.html" />

Depending on the application, a good practice is to redirect the user back to the login page:

根据不同的应用,一个好的做法是将用户重定向到登录页面。

//...
.logout()
.logoutSuccessUrl("/login.html")
//...

4.2. logoutUrl()

4.2.logoutUrl()

Similar to other defaults in Spring Security, the URL that actually triggers the logout mechanism has a default as well – /logout.

与Spring Security中的其他默认值类似,实际触发注销机制的URL也有一个默认值 – /logout

It is, however, a good idea to change this default value, to make sure that no information is published about what framework is used to secure the application:

然而,改变这个默认值是一个好主意,以保护你站点的隐私,防止别人知道你使用的是什么框架来保护应用程序的。

.logout()
.logoutUrl("/perform_logout")

And through XML:

并通过XML。

<logout 
  logout-success-url="/anonymous.html" 
  logout-url="/perform_logout" />

4.3. invalidateHttpSession and deleteCookies

4.3.invalidateHttpSessiondeleteCookies

These two advanced attributes control the session invalidation as well as a list of cookies to be deleted when the user logs out. As such, invalidateHttpSession allows the session to be set up so that it’s not invalidated when logout occurs (it’s true by default).

有两个高级属性控制了会话的失效,以及用户注销时要删除的cookie列表。因此,invalidateHttpSession允许对会话进行设置,以便在注销发生时不会失效(默认为true)。

The deleteCookies method is simple as well:

deleteCookies方法也很简单。

.logout()
.logoutUrl("/perform_logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")

And the XML version:

还有XML版本。

<logout 
  logout-success-url="/anonymous.html" 
  logout-url="/perform_logout"
  delete-cookies="JSESSIONID" />

4.4. logoutSuccessHandler()

4.4.logoutSuccessHandler()

For more advanced scenarios, where the namespace is not flexible enough, the LogoutSuccessHandler bean from the Spring Context can be replaced by a custom reference:

对于更高级的场景,在命名空间不够灵活的情况下,Spring Context中的LogoutSuccessHandler Bean可以被一个自定义引用所取代。

@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
    return new CustomLogoutSuccessHandler();
}

//...
.logout()
.logoutSuccessHandler(logoutSuccessHandler());
//...

The equivalent XML configuration is:

相等的XML配置是。

<logout 
  logout-url="/perform_logout"
  delete-cookies="JSESSIONID"
  success-handler-ref="customLogoutSuccessHandler" />

...
<beans:bean name="customUrlLogoutSuccessHandler" />

Any custom application logic that needs to run when the user successfully logs out can be implemented with custom logout success handler. For example – a simple audit mechanism keeping track of the last page the user was on when they triggered logout:

任何需要在用户成功注销时运行的自定义应用逻辑都可以用自定义注销成功处理器来实现。例如–一个简单的审计机制,跟踪用户触发注销时的最后一个页面。

public class CustomLogoutSuccessHandler extends 
  SimpleUrlLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired 
    private AuditService auditService; 

    @Override
    public void onLogoutSuccess(
      HttpServletRequest request, 
      HttpServletResponse response, 
      Authentication authentication) 
      throws IOException, ServletException {
 
        String refererUrl = request.getHeader("Referer");
        auditService.track("Logout from: " + refererUrl);

        super.onLogoutSuccess(request, response, authentication);
    }
}

Also, keep in mind that this custom bean has the responsibility to determine the destination to which the user is directed after logging out. Because of this, pairing the logoutSuccessHandler attribute with logoutSuccessUrl is not going to work, as both cover similar functionality.

另外,请记住,这个自定义Bean有责任决定用户在注销后被引导到哪个目的地。正因为如此,将logoutSuccessHandler属性与logoutSuccessUrl配对是行不通的,因为两者涵盖了类似的功能。

5. Conclusion

5.结论

In this example, we started by setting up a simple logout sample with Spring Security, and we then discussed the more advanced options available.

在这个例子中,我们首先用Spring Security设置了一个简单的注销样本,然后我们讨论了更高级的选项。

The implementation of this Spring Logout Tutorial can be found in the GitHub project – this is an Eclipse-based project, so it should be easy to import and run as it is.

这个Spring注销教程的实现可以在GitHub项目中找到 – 这是一个基于Eclipse的项目,所以应该很容易导入并按原样运行。

When the project runs locally, the sample HTML can be accessed at:

当项目在本地运行时,可以通过以下网址访问样本HTML。

http://localhost:8080/spring-security-mvc-login/login.html

http://localhost:8080/spring-security-mvc-login/login.html