spring security 3.1.0 控制用户重复登陆
- - CSDN博客架构设计推荐文章通过配置我们可以实现两个需求 1、限制不允许第二个用户登录,2、第二个登陆用户踢掉前一个登陆用户 . 假设你的spring架构已经可以使用了(其他的主要功能完成),需要增加登录限制功能. 注:这里只写配置不写原理(不懂的就问度娘),其实个人认为先配置好跑起来再研究下原理最好了. 通过sessionRegistry可以获取系统当前在线人数和登录用户信息.
<c:if test="${pageContext.request.userPrincipal.name != null}">
<label>
Hi ${pageContext.request.userPrincipal.name} ! Welcome to our site
</label>
</c:if>
<c:choose>
<c:when test="${pageContext.request.userPrincipal.authenticated}">Show something</c:when>
<c:otherwise>Show something else</c:otherwise>
</c:choose>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<sec:authorize access="hasAnyAuthority('ROLE_ADMIN', 'ROLE_USER')" var="isAuthenticated">
</sec:authorize>
<c:out value="${isAuthenticated}"/>
和这个
<sec:authorize access="hasAnyRole('ROLE_ADMIN')">
<a href="delete/${file.id}">Delete</a>
</sec:authorize>
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
// do something...
}
<%@taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>
<sec:authorize access="isAuthenticated()">
<% response.sendRedirect("main"); %>
</sec:authorize>
需要:<global-method-security secured-annotations="enabled" />
@Secured("ROLE_ADMIN")
@RequestMapping(params = "onlyForAdmins")
public ModelAndView onlyForAdmins() {
....
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(params = "onlyForAuthenticated")
public ModelAndView onlyForAuthenticatedUsers() {
....
}
SecurityContextHolder.getContext().getAuthentication() != null &&
SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
//when Anonymous Authentication is enabled
!(SecurityContextHolder.getContext().getAuthentication()
instanceof AnonymousAuthenticationToken)
if (SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
System.out.println("LOGGED IN");
} else {
System.out.println("NOT LOGGED IN");
}
if (!SecurityContextHolder.getContext().getAuthentication().getName().
equals("anonymousUser")) {
System.out.println("LOGGED IN");
} else {
System.out.println("NOT LOGGED IN");
}