Spring Security入門篇——標籤sec:authorize的使用

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

<p>

<sec:authorize ifAllGranted="ROLE_ADMIN">#這裏可以用逗號分隔,加入多個角色

你擁有管理員權限,你可以查看 該頁面<a href="http://blog.163.com/sir_876/blog/admin.jsp"> 管理員進入</a> </sec:authorize> </p> <p> <sec:authorize url='/profile.jsp'>你登陸成功了可以看到 <a href="http://blog.163.com/sir_876/blog/profile.jsp"> 這個頁面</a></sec:authorize>

</p>

頁面標籤的使用與權限配置相對應

<intercept-url            pattern="/admin.jsp"            access="hasRole('ROLE_ADMIN')" />        <intercept-url            pattern="/profile.jsp"            access="isAuthenticated()" />        <intercept-url            pattern="/**"            access="permitAll" />

對比可以看到只有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: 將特殊字符轉義 > –> “&gt”
發佈了10 篇原創文章 · 獲贊 11 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章