知識庫 / Spring / Spring Security RSS 訂閱

Spring Security:檢查用户是否具有角色(Java)

Spring Security
HongKong
5
01:00 PM · Dec 06 ,2025

1. 簡介

在 Spring Security 中,有時需要檢查已認證的用户是否具有特定角色。 這對於在我們的應用程序中啓用或禁用特定功能非常有用

在本教程中,我們將探討 Java 中檢查用户角色的方法,適用於 Spring Security。

2. 在 Java 中檢查用户角色

Spring Security 提供多種在 Java 代碼中檢查用户角色的方法

我們將下面詳細介紹每種方法。

2.1. <em @PreAuthorize</em>>

The first way to check for user roles in Java is to use the <em @PreAuthorize</em>> annotation provided by Spring Security. This annotation can be applied to a class or method, and it accepts a single string value that represents a SpEL expression.

Before we can use this annotation, we must first enable global method security. This can be done in Java code by adding the <em @EnableGlobalMethodSecurity</em>> annotation to any configuration class.

Then, Spring Security provides two expressions we can use with the <em @PreAuthorize</em>> annotation to check user roles:

@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/user/{id}")
public String getUser(@PathVariable("id") String id) {
    ...
}

我們還可以在一個表達式中檢查多個角色:

@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')")
@GetMapping("/users")
public String getUsers() {
    ...
}

在這種情況下,如果用户擁有指定角色中的任何一個,請求將被允許。

如果方法在沒有正確角色的情況下被調用,Spring Security 會拋出異常並重定向到錯誤頁面。

2.2. SecurityContext

The next way we can check for user roles in Java code is with the SecurityContext class.

By default, Spring Security uses a thread-local copy of this class. This means 每個請求在我們的應用程序中都有其自身的安全上下文,其中包含發起請求的用户詳情.

To use it, we simply call the static methods in SecurityContextHolder:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) {
    ...
}

請注意,我們在這裏使用簡化的權限名稱,而不是完整的角色名稱。

這種方法在我們需要進行更精細的檢查時非常有效——例如,對單個方法的特定部分。但是,如果使用 Spring Security 的全局上下文持有者模式,這種方法將不起作用

2.3. UserDetailsService

通過 UserDetailsService,我們可以將Java代碼中的用户角色查找方式擴展到第三種方法。這是一個可以注入到應用程序的 Bean,並在需要時調用它:

@GetMapping("/users")
public String getUsers() {
    UserDetails details = userDetailsService.loadUserByUsername("mike");
    if (details != null && details.getAuthorities().stream()
      .anyMatch(a -> a.getAuthority().equals("ADMIN"))) {
        // ...
    }
}

再次強調,這裏必須使用權威名稱,而不是包含職稱和前綴的全稱。

這種方法的優勢在於,我們可以檢查任何用户的角色,而不僅僅是發起請求的用户。

2.4 Servlet 請求

如果使用 Spring MVC,我們也可以在 Java 中使用 HttpServletRequest 類來檢查用户角色:

@GetMapping("/users")
public String getUsers(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        ...
    }
}

3. 結論

在本文中,我們探討了多種使用 Java 代碼和 Spring Security 驗證角色的方法。

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

發佈 評論

Some HTML is okay.