Security框架可以精確控制頁面的一個按鈕、鏈接,它在頁面上權限的控制實際上是通過它提供的標簽來做到的
Security共有三類標簽authorize authentication accesscontrollist ,第三個標簽不在這里研究
前提:項目需要引用spring-security-taglibs-3.05,jstl1.2的jar包,頁面加入:<%@ taglib prefix=”sec” uri=”http://www.springframework.org/security/tags” %>
本文配置
一、authorize
對應的類: org.springframework.security.taglibs.authz.AuthorizeTag
attribute: access url method ifNotGranted ifAllGranted ifAnyGranted
使用方式:見SimpleDemo的index.jsp
<sec:authorize ifAllGranted="ROLE_ADMIN">#這里可以用逗號分隔,加入多個角色
你擁有管理員權限,你可以查看 該頁面 管理員進入 </sec:authorize>
<sec:authorize url='/profile.jsp'>你登陸成功了可以看到 這個頁面</sec:authorize>
頁面標簽的使用與權限配置相對應
對比可以看到只有ROLE_ADMIN角色的用戶才能訪問admin.jsp,通過認證的用戶都可以訪問profile.jsp
從標簽源碼可以知道,authorize標簽判斷順序是: access->url->ifNotGranted->ifAllGranted->ifAnyGranted 但他們的關系是“與”: 即只要其中任何一個屬性不滿足則該標簽中間的內容將不會顯示給用戶,舉個例子:
<sec:authorize ifAllGranted=”ROLE_ADMIN,ROLE_MEMBER” ifNotGranted=”ROLE_SUPER”>滿足才會顯示給用戶 </sec:authorize>
標簽中間的內容只有在當前用戶擁有ADMIN,MEMBER角色,但不擁有SUPER權限時才會顯示
access屬性是基於角色判斷,url屬性是基於訪問路徑判斷,與security.xml配置對應
對於ifAllGranted ,ifNotGranted,ifAnyGranted屬性的理解可以與集合api類比
Collection grantedAuths :當前用戶擁有的權限
Collection requiredAuths : 當前要求的權限,即ifAllGranted ,ifNotGranted,ifAnyGranted 屬性的值
滿足ifAllGranted: 只需要grantedAuths.containsAll(requiredAuths);返回true即可
滿足ifAnyGranted: 只需要grantedAuths.retainAll(requiredAuths);有內容即可(兩集合有交集)
滿足ifNotGranted:與Any相反,如果沒有交集即可
二、authentication
對應的類: org.springframework.security.taglibs.authz.AuthenticationTag
attribute: property(required) var htmlEscape scope
使用方式:
<sec:authentication property=’name’ />
<sec:authentication property=’principal.username’ />
<sec:authentication property=’principal.enabled’ />
<sec:authentication property=’principal.accountNonLocked’ />
主要用來顯示authentication屬性,
var scope: 將property的值以var設置到scope域中
htmlEscape: 將特殊字符轉義 > –> “>”