方法一叫编、JSP中檢查user principal
<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}"/>
和這個(gè)
<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...
}
方法四、 使用標(biāo)簽庫
<%@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");
}