1. 概述
在本教程中,我們將探討 Spring Security Taglibs,它提供對訪問安全信息和在 JSPs 中應用安全約束的基本支持。
2. Maven 依賴
首先,我們需要將 <a href="https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs">spring-security-taglibs</a> 依賴添加到我們的 <em>pom.xml</em> 文件中:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>6.1.5</version>
</dependency>3. 聲明標籤庫
在 JSP 文件頂部導入標籤庫,我們才能使用標籤:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>添加完此項後,我們就能使用sec前綴來指定Spring Security的標籤。
4. authorize 標籤
該標籤用於在應用程序中控制用户對特定資源的訪問權限。它允許您根據用户的角色、權限或其他條件,授予或拒絕訪問請求。
4.1. 訪問表達式 (access)
在我們的應用程序中,我們可能需要顯示僅供特定角色或用户的相關信息。
當這種情況發生時,我們可以使用 authorize 標籤:
<sec:authorize access="!isAuthenticated()">
Login
</sec:authorize>
<sec:authorize access="isAuthenticated()">
Logout
</sec:authorize>此外,我們還可以檢查已認證的用户是否具有特定的角色:
<sec:authorize access="hasRole('ADMIN')">
Manage Users
</sec:authorize>我們可以使用任何 Spring Security 表達式作為 access 的值:
- hasAnyRole('ADMIN','USER') 如果當前用户擁有任何指定的角色,則返回 true
- isAnonymous() 如果當前 principal 是匿名用户,則返回 true
- isRememberMe() 如果當前 principal 是記住我用户,則返回 true
- isFullyAuthenticated() 如果用户已認證且既不是匿名用户也不是記住我用户,則返回 true
4.2. URL
除此之外,我們可以檢查是否有權限向特定 URL 發送請求的用户:
<sec:authorize url="/userManagement">
<a href="/userManagement">Manage Users</a>
</sec:authorize>4.3. 調試
如果我們需要對UI擁有更大的控制權,例如在測試場景中,可以避免Spring Security跳過渲染這些未授權部分。 可以通過在,例如,我們的<em>application.properties</em> 文件中設置spring.security.disableUISecurity=true 來實現。
當我們這樣做時,<em>authorize</em> 標籤不會隱藏其內容。 而是,它會將內容用<span class=”securityHiddenUI”>… </span> 標籤包裹。 然後,我們可以使用一些CSS自定義渲染。
不過請記住,通過CSS隱藏內容並不安全! 用户可以簡單地查看源代碼來查看未授權內容。
5. authentication 標籤
在其他時候,我們可能想顯示已登錄用户的詳細信息,例如在網站上説“歡迎回來,卡羅爾!”為此,我們使用 authentication 標籤:
<sec:authorize access="isAuthenticated()">
Welcome Back, <sec:authentication property="name"/>
</sec:authorize>6. csrfInput 標籤
希望我們應用程序中啓用了 Spring Security 的 CSRF 防禦!
如果啓用了,則 Spring Security 已經在 <form:form> 標籤內自動插入 CSRF 隱藏表單輸入。
但是,如果我們要使用 <form> 標籤,我們可以手動指定 Spring Security 應該放置該隱藏輸入字段的位置,使用 csrfInput:
<form method="post" action="/do/something">
<sec:csrfInput />
Text Field:<br />
<input type="text" name="textField" />
</form>如果未啓用 CSRF 保護,則此標籤將輸出空內容。
7. csrfMetaTags 標籤
或者,如果我們想要在 JavaScript 中訪問 CSRF 令牌, 我們通常會將其作為元數據標籤插入。
我們可以使用 csrfMetaTags 標籤來實現:
<html>
<head>
<title>JavaScript with CSRF Protection</title>
<sec:csrfMetaTags />
<script type="text/javascript" language="javascript">
var csrfParameter = $("meta[name='_csrf_parameter']").attr("content");
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
var csrfToken = $("meta[name='_csrf']").attr("content");
</script>
</head>
<body>
...
</body>
</html>再次強調,如果未啓用 CSRF 保護,則此標籤將不會輸出任何內容。
8. 結論
在本文中,我們重點介紹了一些常見的 Spring Security taglib 使用案例。
正如我們所學到的,它們對於渲染認證和授權感知型 JSP 內容非常有用。