Spring Security – 配置不同URL

Spring Security
Remote
1
07:53 AM · Nov 30 ,2025

1. 概述

在本教程中,我們將探討如何配置 Spring Security 以針對不同的 URL 模式使用不同的安全配置。

這在應用程序需要針對某些操作提供更高級別的安全性,而其他操作則允許所有用户執行時非常有用。

2. 部署

我們首先開始設置應用程序。

我們需要 WebSecurity 依賴項來創建此服務。我們首先通過將以下依賴項添加到 pom.xml 文件中來開始:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-security</artifactId> 
</dependency>

3. 創建 API

我們將創建一個 RESTful Web 服務,包含兩個 API:一個產品 API 和一個客户 API。為了實現這一點,我們將設置兩個控制器。

3.1. 產品 API

讓我們創建 ProductController。它包含一個方法, getProducts,它返回一個產品列表:

@RestController("/products")
public class ProductController {
    
    @GetMapping
    public List<Product> getProducts() {
        return new ArrayList<>(Arrays.asList(
          new Product("Product 1", "Description 1", 1.0),
          new Product("Product 2", "Description 2", 2.0)
        ));
    }
}

3.2. 客户 API

同樣, 讓我們定義 CustomerController

@RestController("/customers")
public class CustomerController {
    
    @GetMapping("/{id}")
    public Customer getCustomerById(@PathVariable("id") String id) {
        return new Customer("Customer 1", "Address 1", "Phone 1");
    }
}

在典型的 Web 應用程序中,所有用户,包括訪客用户都可以獲取產品列表。

但是,通過 ID 獲取客户的詳細信息似乎只有管理員才能執行。因此,我們將以一種能夠啓用這種方式定義我們的安全配置。

4. Set Up the Security Configuration

當我們向項目添加 Spring Security 時,它將默認禁用所有 API 的訪問。因此,我們需要配置 Spring Security 以允許訪問 API。

讓我們創建一個 SecurityConfiguration 類:

@Configuration
public class SecurityConfiguration {

     @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http.authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/products/**"))
                .permitAll())
            .authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/customers/**"))
                .hasRole("ADMIN")
                .anyRequest()
                .authenticated())
            .httpBasic(Customizer.withDefaults())
            .build();
    }
}

在這裏,我們創建了一個 SecurityFilterChain Bean 以配置應用程序的安全性。

此外,為了準備基本身份驗證,我們需要為我們的應用程序配置用户。

我們將讀取代碼中的每一部分以更好地理解它。

4.1. Allowing Requests to the Products API

  • 此方法告訴 Spring 使用以下規則來授權請求。
  • 此項指定用於安全配置應用的 URL 模式。我們將其與 permitAll() 操作進行鏈接。如果請求路徑包含 “/products””,則允許該請求到達控制器。
  • and() method.">我們可以使用 and() 方法添加更多規則到我們的配置中。

這標誌着一個規則鏈的結束。後續的規則也將應用於請求。因此,我們需要確保我們的規則不衝突。一個好的做法是在頂部定義通用規則,在底部定義更具體的規則。

4.2. Allow Only Admin Access to the Customer API

現在讓我們看一下配置的第二部分:

  • authorizeRequests() method.">為了啓動一個新的規則,我們可以再次使用 authorizeRequests() 方法。
  • 如果 URL 路徑包含 “/customers””,則檢查請求發起者是否具有 ADMIN 角色。

如果用户未經過身份驗證,則會返回一個 “401 Unauthorized” 錯誤。如果用户沒有正確的角色,則會返回一個 “403 Forbidden” 錯誤。

4.3. Default Rule

我們已經添加了匹配某些請求的規則。現在我們需要定義剩餘請求的默認行為。

anyRequest().authenticated()anyRequest() 定義了一個用於任何未匹配先前規則的請求的規則鏈anyRequest()。在這種情況下,此類請求將繼續,只要它們經過身份驗證。

請注意,配置中只能有一個默認規則,並且它需要位於末尾。如果我們嘗試在添加默認規則之後添加規則,則會收到錯誤 – “Can’t configure antMatchers after anyRequest”

5. 測試

讓我們使用 cURL 測試兩個 API。

5.1. 測試產品 API

$ curl -i http://localhost:8080/products
[
  {
    "name": "Product 1",
    "description": "Description 1",
    "price": 1.0
  },
  {
    "name": "Product 2",
    "description": "Description 2",
    "price": 2.0
  }
]

我們得到兩個產品作為響應,符合預期。

5.2. 測試客户 API

$ curl -i http://localhost:8080/customers/1

響應體為空。

如果檢查響應頭,我們會看到“401 Unauthorized”狀態。這是因為訪問客户 API 僅允許具有 ADMIN 角色的已認證用户。

現在,讓我們在請求中添加身份驗證信息後再次嘗試:

$ curl -u admin:password -i http://localhost:8080/customers/1 
{
  "name": "Customer 1",
  "address": "Address 1",
  "phone": "Phone 1"
}

太棒了!我們現在可以訪問客户 API。

6. 結論

在本教程中,我們學習瞭如何在 Spring Boot 應用程序中設置 Spring Security。我們還介紹瞭如何使用 antMatchers() 方法配置特定 URL 模式的訪問權限。

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

發佈 評論

Some HTML is okay.