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

时间:2013-12-30 22:03:56

标签: java spring spring-security

编辑 - 1

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

 </security:http>

编辑 - 1结束 http://pastie.org/8588538第1到第6行是注销用户的正确方法吗?因为当我这样做时,用户似乎暂时在页面上注销,但随后可以使用相同的登录名再次访问其他页面。似乎第31行和第38行正在制作一个新的会话cookie。但是如何?

@RequestMapping(value = "/logout" )
    public String logout(ModelMap model, HttpServletRequest request){
        request.getSession(true).invalidate();
        System.out.println("logout user page shown--------------------");
        return "/login/logout";       
   }


200 OK

GET /logout

200 OK

localhost:8080

5.7 KB

127.0.0.1:8080



225ms
HeadersResponseHTMLCacheCookies
Response Headersview source
Content-Language    en
Content-Length  5864
Content-Type    text/html;charset=ISO-8859-1
Date    Mon, 30 Dec 2013 21:38:59 GMT
Server  Apache-Coyote/1.1
Set-Cookie  JSESSIONID=4B961D14E4B3096368BCC5F9A55874BC; Path=/ttmaven/; HttpOnly

Request Headersview source
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Cookie  JSESSIONID=A0E89C909D0A7F7BE93EC737130E9A31
Host    localhost:8080
Referer http://localhost:8080/ttmaven/users/home
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0

3 个答案:

答案 0 :(得分:3)

您就是这样做的:

SecurityContextHolder.getContext().setAuthentication(null);

Spring Security还提供了已实现的登录/注销功能,以下是配置自定义注销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>

答案 1 :(得分:1)

在2020年,您应该使用SecurityContextLogoutHandler

答案 2 :(得分:0)

HTML页面

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

我们只需要在控制器中映射 / logout 链接。

@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. }