**
spring security logout(spring security登出示例)
**
在学习实现spring security登出的时候发现了一篇外文,感觉写的挺好,这里斗胆尝试翻译出来,原文链接:http://websystique.com/spring-security/spring-security-4-logout-example/
翻译如下:
这篇文章的是展示如何通过编码的方式实现spring security的用户登出操作。通过浏览器后退键也会触发登出。
通常来说,是需要在你的页面中提供给用户一个登出链接的,就像下面的代码中所展示的:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Admin page</title>
</head>
<body>
Dear <strong>${user}</strong>, Welcome to Admin Page.
<a href="<c:url value="/logout" />">Logout</a>
</body>
</html>
注:代码里面用到了jstl的标签,如果想要使用上述代码,需要在项目中导入jstl的jar包。
没有任何特别的地方。现在只需要在springmvc的控制器中,标记出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.
}
(上述代码逻辑解析)我们首先是确定,用户点击登出链接的时候,是否是在已验证的前提下(这里可能是用户的session失效等情况)。
SecurityContextHolder.getContext().getAuthentication()
如果上述代码获取的Authentication对象不为空,然后我们调用
SecurityContextLogoutHandler().logout(request, response, auth)
来对用户进行登出操作。
登出的操作需要进行下面几个步骤:
- 使HTTP Session失效,然后解绑Session上的所以已绑定的对象。
- 将用户的认证信息从spring security的SecurityContext中移除,以防止并发请求的问题。
从当前线程中,完全的清除相关的属性值。
到这就完成了。