Java 如何在spring security中正确注销用户

Java 如何在spring security中正确注销用户,java,spring,spring-security,Java,Spring,Spring Security,编辑-1 <security:logout invalidate-session="true" logout-success-url="/logout" logout-url="/logoutfail"/> </security:http> 这就是你如何做到的: SecurityContextHolder.getContext().setAuthentication(null); SpringSecurity还提供了已经实现的登录/注销功能

编辑-1

<security:logout
    invalidate-session="true"
    logout-success-url="/logout"
    logout-url="/logoutfail"/>

 </security:http>
这就是你如何做到的:

SecurityContextHolder.getContext().setAuthentication(null);
SpringSecurity还提供了已经实现的登录/注销功能,下面是如何配置自定义注销URL。您不必创建任何控制器/请求映射

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http auto-config="true" use-expressions="true">
        <logout logout-url="/custom_logout_url" />
    </http>
</beans:beans>

HTML页面

<li><a href="#" th:href="@{/logout}"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li>

2020年,你应该使用。

hmm。。为什么
request.getSession(true).invalidate()不起作用?它将使会话无效,并创建一个新的(而不是上一个)会话。因此,登录的会话无效。但我还是无法理解,如果您使用的是这个XML配置:,那么就不需要实现控制器和“/logout”的请求映射,Spring Security会为您处理它。只需从控制器中删除整个logout()方法。那么如何注销用户呢?2.我必须在注销或注销失败后显示一些成功/错误页面。不?哦,我知道发生了什么。当您转到logout()方法时,您的用户应该已经注销了。然后他的会话再次无效。因此,在logout()方法中,只返回视图名称,不需要其他方法调用。另外,在页面中添加一个debug DIV,并在其中打印当前用户信息,以便查看谁已登录/未登录。希望能有帮助。这就是奇怪的地方。以前的用户是“Admin”,现在我注销了,仍然可以看到“Admin”
<li><a href="#" th:href="@{/logout}"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li>
@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){    
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }
    return "redirect:/login?logout"; //You can redirect wherever you want, but generally it's a good practice to show login screen again.
}