知識庫 / Spring / Spring MVC RSS 訂閱

Spring Security 與 Thymeleaf

Spring MVC,Spring Security
HongKong
9
02:04 PM · Dec 06 ,2025

1. 概述

在本快速教程中,我們將重點介紹 Spring Security 與 Thymeleaf 的使用。

我們將創建一個 Spring Boot 應用程序,以演示安全方言的使用。

我們選擇的前端技術是 Thymeleaf – 一個現代的服務器端 Web 模板引擎,與 Spring MVC 框架具有良好的集成。有關更多詳細信息,請參閲我們在該項上撰寫的介紹文章。

最後,Spring Security Dialect 是 Thymeleaf 擴展模塊,自然地幫助將兩者集成在一起。

我們將使用我們在 Spring Boot 教程文章中構建的簡單項目;我們還有一個使用 Spring 和 Thymeleaf 的 Thymeleaf 教程,其中可以找到標準的 Thymeleaf 配置。

2. 依賴項

首先,我們需要將新的依賴項添加到我們的 Maven <em pom.xml</em> 中:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>

建議始終使用最新版本,我們可以在 Maven Central 上獲取。

3. Spring Security 配置

接下來,我們定義 Spring Security 的配置。

我們需要至少兩個不同的用户來演示安全方言的使用:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    // [...] 
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) 
      throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
          .and()
          .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
    }
    
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

如我們所見,在 configureGlobal(AuthenticationManagerBuilder auth) 中,我們定義了兩個用户,分別帶有用户名和密碼。我們可以使用它們來訪問我們的應用程序。

我們的用户擁有不同的角色:ADMINUSER,以便我們可以根據角色向他們呈現特定的內容。

4. 安全方言 (Security Dialect)

安全方言允許我們根據用户角色、權限或其他安全表達式條件地顯示內容。 它還賦予我們訪問 Spring 的 Authentication 對象。

讓我們來看一下包含安全方言示例的首頁:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Welcome to Spring Security Thymeleaf tutorial</title>
    </head>
    <body>
        <h2>Welcome</h2>
        <p>Spring Security Thymeleaf tutorial</p>
        <div sec:authorize="hasRole('USER')">Text visible to user.</div>
        <div sec:authorize="hasRole('ADMIN')">Text visible to admin.</div>
        <div sec:authorize="isAuthenticated()">
            Text visible only to authenticated users.
        </div>
        Authenticated username:
        <div sec:authentication="name"></div>
        Authenticated user roles:
        <div sec:authentication="principal.authorities"></div>
    </body>
</html>

我們能看到 Spring Security Dialect 相關的屬性:sec:authorizesec:authentication

讓我們逐一討論這些屬性。

4.1. 理解 <em sec:authorize</em>

簡單來説,我們使用 `` 屬性來控制顯示的內容。

例如,如果我們只想向擁有 USER 角色的用户顯示內容,我們可以這樣做:<div sec:authorize=”hasRole(‘USER’)”>.

並且,如果我們想擴大對所有已認證用户的訪問權限,我們可以使用以下表達式:

<div sec:authorize=”isAuthenticated()”>.

4.2. 理解 <em >sec:authentication</em >

Spring Security 的 <a href="https://docs.spring.io/spring-security/site/docs/5.0.3.RELEASE/api/org/springframework/security/core/Authentication.html" rel="noopener">Authentication</a> 接口提供了關於已認證的主體或認證請求的有用方法。

在 Thymeleaf 中訪問認證對象,我們可以簡單地使用 <div sec:authentication=”name”><div sec:authentication=”principal.authorities”>

前者允許我們訪問已認證用户的名稱,後者允許我們訪問已認證用户的角色。

5. 總結

本文介紹了在簡單的 Spring Boot 應用中使用 Spring Security 支持和 Thymeleaf 的方法。

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

發佈 評論

Some HTML is okay.