Spring Security Taglibs 簡介

Spring Security
Remote
1
05:11 AM · Nov 30 ,2025

1. 概述

在本教程中,我們將探討 Spring Security Taglibs,它提供對訪問安全信息和在JSPs中應用安全約束的基本支持。

2. Maven 依賴項首先,讓我們將 spring-security-taglibs 依賴項添加到我們的 pom.xml 中:

<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. The authorize Tag

4.1. access Expressions

在我們的應用程序中,我們可能有一些信息,僅需向特定角色或用户顯示。

當這種情況發生時,我們可以使用 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() 返回 true 如果當前 principal 是一個匿名用户
  • isRememberMe() 返回 true 如果當前 principal 是一個記住我用户
  • isFullyAuthenticated() 返回 true 如果用户已認證並且既不是匿名用户也不是記住我用户

4.2. url

除此之外,我們可以檢查授權向特定 URL 發送請求的用户:

<sec:authorize url="/userManagement">
    <a href="/userManagement">Manage Users</a>
</sec:authorize>

4.3. Debugging

可能存在我們想要對 UI 具有更多控制的情況,例如在測試場景中。而不是讓 Spring Security 跳過渲染這些未授權部分,我們可以將 spring.security.disableUISecurity 設置為 true,例如在我們的 application.properties 文件中。

當我們這樣做時,authorize 標籤不會隱藏其內容, 而是會將內容用 <span class=”securityHiddenUI”>… </span> 標籤包裹,然後我們可以使用一些 CSS 自定義渲染。

請記住,通過 CSS 隱藏內容不安全!  用户可以簡單地查看源代碼以查看未授權內容。

5. 身份驗證 標籤

在其他時候,我們可能需要顯示已登錄用户的詳細信息,例如在網站上顯示“歡迎回來,卡羅爾!”。

為此,我們使用 身份驗證 標籤:

<sec:authorize access="isAuthenticated()">
    Welcome Back, <sec:authentication property="name"/>
</sec:authorize>

6. The csrfInput 標籤

希望我們已經在應用程序中啓用了 Spring Security 的 CSRF 防禦!

如果啓用了,Spring Security 已經在 <form:form> 標籤內自動插入一個 CSRF 隱藏表單輸入字段。

但是,如果希望使用 <form> 標籤,我們可以手動指定 Spring Security 應該放置該隱藏輸入字段的位置,使用 csrfInput

<form method="post" action="/do/something">
    <sec:csrfInput />
    文本框:
<input type="text" name="textField" /> </form>

如果 CSRF 保護未啓用,此標籤將輸出 nothing。

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 內容非常有用。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.