常用内建表示式
ps: 定義在 SecurityExpressionRoot| 表示式 | 說明 |
|---|---|
| hasRole('role') | 當前的 User 擁有指定的 Role 就回傳 true |
| hasAnyRole('role1', 'role2') | 當前的 User 擁有任一個 Role 就回傳 true |
| principal | 當前的 User 的 Principal 物件 |
| authentication | 當前的 User 的 Authentication 物件 |
| permitAll | 總是為 true |
| denyAll | 總是為 false |
| isAnonymous() | 當前的 User 是匿名登入就回傳 true |
| isRememberMe() | 當前的 User 是透過 remember-me 登入就回傳 true |
| isAuthenticated() | 當前的 User 不是匿名登入就回傳 true |
| isFullyAuthenticated() | 當前的 User 不是匿名登入或 remember-me 登入就回傳 true |
在方法執行前的驗證
驗證 User 角色
@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);
驗證參數值是否等於 User 名稱
@PreAuthorize("#contact.name == authentication.name")
public void doSomething(Contact contact);
驗證 User 角色以及來源 IP 區間
@PreAuthorize("hasRole('admin') and hasIpAddress('192.168.1.0/24')")
public void doSomething(Contact contact);
在方法內的驗證
取得角色驗證
@RequestMapping("/index")
public void index(HttpServletRequest request) {
System.out.println(request.isUserInRole("ROLE_USER"));
if (request.isUserInRole("admin")) {
System.out.println("is admin");
}
}
在 JSP 的驗證
取得 User 名稱
<sec:authentication property="name"/> <sec:authentication property="principal.username"/>
取得 User IP
<sec:authentication property="details.remoteAddress"/>
取得 User SessionId
<sec:authentication property="details.sessionId"/>
驗證角色為 admin 才顯示
<sec:authorize access="hasRole('admin')">
<div>is admin</div>
</sec:authorize>
驗證角色為 admin 存入變數 isAdmin
<sec:authorize var="isAdmin" access="hasRole('admin')" />
<c:if test="isAdmin">
<div>is admin</div>
</c:if>
參考自:15. Expression-Based Access Control
0 回應:
張貼留言