最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Security中的 @PreAuthorize 注解使用方法和示例代碼

 更新時(shí)間:2026年01月23日 14:33:49   作者:小猿、  
@PreAuthorize是SpringSecurity中用于方法級(jí)權(quán)限控制的重要注解,本文詳細(xì)介紹了@PreAuthorize的使用方法,通過(guò)合理使用@PreAuthorize,可以實(shí)現(xiàn)細(xì)粒度的權(quán)限控制,確保應(yīng)用程序的安全性,感興趣的朋友跟隨小編一起看看吧

概述

在 Spring Security 框架中,@PreAuthorize注解是實(shí)現(xiàn)方法級(jí)權(quán)限控制的重要工具。它提供了靈活而強(qiáng)大的方式來(lái)保護(hù)應(yīng)用程序中的方法,確保只有具備特定權(quán)限的用戶才能訪問(wèn)。本文將詳細(xì)介紹@PreAuthorize注解的使用方法、應(yīng)用場(chǎng)景和示例代碼。

什么是 @PreAuthorize 注解

@PreAuthorize是 Spring Security 提供的一個(gè)方法級(jí)安全注解,用于在方法執(zhí)行前進(jìn)行權(quán)限檢查。它可以基于表達(dá)式來(lái)定義訪問(wèn)規(guī)則,只有當(dāng)表達(dá)式計(jì)算結(jié)果為true時(shí),方法才會(huì)被執(zhí)行;否則將拒絕訪問(wèn)并拋出AccessDeniedException。

與傳統(tǒng)的 URL 級(jí)別的安全控制相比,@PreAuthorize提供了更細(xì)粒度的權(quán)限控制,能夠直接作用于服務(wù)層或控制器層的方法。

啟用 @PreAuthorize 注解

要使用@PreAuthorize注解,首先需要在 Spring 配置類(lèi)中啟用全局方法安全:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    // 配置內(nèi)容
}

Spring Boot 3.4.3 中的配置方式

Spring Boot 3.x 中,@PreAuthorize的啟用方式與之前版本不同,主要變化是使用@EnableMethodSecurity替代了舊的@EnableGlobalMethodSecurity。

基礎(chǔ)配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableMethodSecurity(prePostEnabled = true) // 啟用@PreAuthorize支持
public class SecurityConfig {
    // 密碼編碼器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    // 配置用戶信息(示例使用內(nèi)存用戶)
    @Bean
    public UserDetailsService userDetailsService() {
        return new InMemoryUserDetailsManager(
            User.withUsername("admin")
                .password(passwordEncoder().encode("admin123"))
                .roles("ADMIN")
                .build(),
            User.withUsername("user")
                .password(passwordEncoder().encode("user123"))
                .roles("USER")
                .build(),
            User.withUsername("editor")
                .password(passwordEncoder().encode("editor123"))
                .roles("EDITOR")
                .build()
        );
    }
}

注意:Spring Security 6.x 默認(rèn)不再自動(dòng)添加 "ROLE_" 前綴,hasRole('ADMIN')實(shí)際檢查的是 "ADMIN" 權(quán)限,而非舊版本的 "ROLE_ADMIN"。

常用表達(dá)式語(yǔ)法

@PreAuthorize注解的值是一個(gè) SpEL 表達(dá)式,常用表達(dá)式包括:

  • hasRole('ADMIN'):檢查用戶是否具有指定角色
  • hasAnyRole('ADMIN', 'USER'):檢查用戶是否具有任意指定角色
  • hasAuthority('DOCUMENT_DELETE'):檢查用戶是否具有指定權(quán)限
  • hasAnyAuthority('CREATE', 'UPDATE'):檢查用戶是否具有任意指定權(quán)限
  • principal:獲取當(dāng)前用戶的主體對(duì)象
  • authentication:獲取當(dāng)前用戶的認(rèn)證對(duì)象
  • isAuthenticated():檢查用戶是否已認(rèn)證
  • permitAll():允許所有用戶訪問(wèn)
  • denyAll():拒絕所有用戶訪問(wèn)
  • #parameter:引用方法參數(shù)(如#id引用方法中的 id 參數(shù))
  • @beanName.method(arguments):調(diào)用 Spring 管理的 Bean 的方法

實(shí)際應(yīng)用場(chǎng)景與示例

1. 基礎(chǔ)訪問(wèn)控制

在控制器層使用@PreAuthorize控制 API 訪問(wèn)權(quán)限:

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
    // 公開(kāi)接口,所有人可訪問(wèn)
    @GetMapping("/public")
    @PreAuthorize("permitAll()")
    public String publicResource() {
        return "This is a public resource";
    }
    // 需認(rèn)證后訪問(wèn)
    @GetMapping("/protected")
    @PreAuthorize("isAuthenticated()")
    public String protectedResource() {
        return "This is a protected resource";
    }
    // 僅管理員可訪問(wèn)
    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String adminResource() {
        return "This is an admin resource";
    }
    // 管理員或編輯可訪問(wèn)
    @GetMapping("/editor")
    @PreAuthorize("hasAnyRole('ADMIN', 'EDITOR')")
    public String editorResource() {
        return "This is an editor resource";
    }
}

2. 服務(wù)層方法權(quán)限控制

在服務(wù)層對(duì)業(yè)務(wù)方法進(jìn)行權(quán)限控制:

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class DocumentService {
    // 需要文檔創(chuàng)建權(quán)限
    @PreAuthorize("hasAuthority('DOCUMENT_CREATE')")
    public String createDocument(String content) {
        // 業(yè)務(wù)邏輯:創(chuàng)建文檔
        return "Document created with content: " + content;
    }
    // 需要文檔刪除權(quán)限或管理員角色
    @PreAuthorize("hasAuthority('DOCUMENT_DELETE') or hasRole('ADMIN')")
    public void deleteDocument(Long documentId) {
        // 業(yè)務(wù)邏輯:刪除文檔
        System.out.println("Deleting document with ID: " + documentId);
    }
}

3. 基于方法參數(shù)的權(quán)限驗(yàn)證

確保用戶只能操作自己有權(quán)限的數(shù)據(jù):

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class UserService {
    // 確保用戶只能更新自己的信息
    @PreAuthorize("#userId == authentication.principal.id")
    public void updateUserProfile(Long userId, String newName) {
        // 業(yè)務(wù)邏輯:更新用戶信息
        System.out.println("Updating profile for user " + userId + " to " + newName);
    }
    // 管理員可以查看任何用戶,普通用戶只能查看自己
    @PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")
    public String getUserDetails(Long userId) {
        // 業(yè)務(wù)邏輯:獲取用戶詳情
        return "Details for user " + userId;
    }
}

4. 調(diào)用自定義 Bean 進(jìn)行復(fù)雜權(quán)限判斷

對(duì)于復(fù)雜的權(quán)限邏輯,可以封裝到專(zhuān)門(mén)的安全服務(wù)中:

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/projects")
public class ProjectController {
    // 項(xiàng)目所有者或管理員可以更新項(xiàng)目
    @PutMapping("/{projectId}")
    @PreAuthorize("@projectSecurityService.isOwner(#projectId, authentication.principal) or hasRole('ADMIN')")
    public String updateProject(@PathVariable Long projectId, @RequestBody String projectData) {
        return "Project " + projectId + " updated successfully";
    }
}

對(duì)應(yīng)的自定義安全服務(wù):

import org.springframework.stereotype.Component;
@Component("projectSecurityService")
public class ProjectSecurityService {
    /**
     * 檢查用戶是否是項(xiàng)目的所有者
     * @param projectId 項(xiàng)目ID
     * @param principal 當(dāng)前用戶主體
     * @return 是否為所有者
     */
    public boolean isOwner(Long projectId, Object principal) {
        // 在實(shí)際應(yīng)用中,這里會(huì)查詢數(shù)據(jù)庫(kù)驗(yàn)證項(xiàng)目所有權(quán)
        // 這里僅作示例:假設(shè)用戶"user"擁有ID小于100的項(xiàng)目
        String username = principal.toString();
        return "user".equals(username) && projectId < 100;
    }
}

處理權(quán)限不足的情況

當(dāng)@PreAuthorize表達(dá)式返回false時(shí),Spring Security 會(huì)拋出AccessDeniedException??梢酝ㄟ^(guò)全局異常處理器統(tǒng)一處理:

import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public String handleAccessDenied(AccessDeniedException ex) {
        return "Access denied: You don't have permission to perform this action";
    }
}

注意事項(xiàng)

  • 密碼安全:示例中使用了 BCrypt 密碼編碼器,生產(chǎn)環(huán)境務(wù)必避免使用明文或{noop}無(wú)加密方式。
  • 角色與權(quán)限區(qū)別hasRole()hasAuthority()的區(qū)別在于,hasRole()會(huì)自動(dòng)將角色名轉(zhuǎn)換為大寫(xiě),而hasAuthority()則嚴(yán)格匹配。
  • 性能考慮:復(fù)雜的 SpEL 表達(dá)式可能影響性能,對(duì)于高頻調(diào)用的方法,應(yīng)優(yōu)化權(quán)限判斷邏輯。
  • 測(cè)試:使用@PreAuthorize后,需要為不同角色和權(quán)限的用戶編寫(xiě)充分的測(cè)試用例。
  • 與 URL 安全控制的配合@PreAuthorize通常與 URL 級(jí)別的安全控制配合使用,形成多層次的安全防護(hù)。

總結(jié)

在 Spring Boot 3.4.3 中,@PreAuthorize注解通過(guò)@EnableMethodSecurity啟用,提供了強(qiáng)大而靈活的方法級(jí)權(quán)限控制能力。它支持復(fù)雜的 SpEL 表達(dá)式,能夠?qū)崿F(xiàn)基于角色、權(quán)限、用戶屬性和業(yè)務(wù)邏輯的細(xì)粒度權(quán)限判斷。

合理使用@PreAuthorize可以顯著提高應(yīng)用程序的安全性,確保敏感操作和數(shù)據(jù)得到適當(dāng)?shù)谋Wo(hù)。在實(shí)際開(kāi)發(fā)中,應(yīng)根據(jù)業(yè)務(wù)需求選擇合適的權(quán)限控制策略,并遵循最小權(quán)限原則,僅為用戶分配必要的權(quán)限。

到此這篇關(guān)于Spring Security中的 @PreAuthorize 注解使用方法和示例代碼的文章就介紹到這了,更多相關(guān)Spring Security @PreAuthorize 注解使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 教你如何在Intellij IDEA中集成Gitlab

    教你如何在Intellij IDEA中集成Gitlab

    今天來(lái)簡(jiǎn)單說(shuō)下,如何在IDEA中集成gitlab項(xiàng)目,默認(rèn)情況下IDEA中的 VCS => Checkout From Version Control 選項(xiàng)中是沒(méi)有g(shù)itlab這一項(xiàng)的,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2023-10-10
  • Spring cache整合redis代碼實(shí)例

    Spring cache整合redis代碼實(shí)例

    這篇文章主要介紹了Spring cache整合redis代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • java多線程實(shí)現(xiàn)同步鎖賣(mài)票實(shí)戰(zhàn)項(xiàng)目

    java多線程實(shí)現(xiàn)同步鎖賣(mài)票實(shí)戰(zhàn)項(xiàng)目

    本文主要介紹了java多線程實(shí)現(xiàn)同步鎖賣(mài)票實(shí)戰(zhàn)項(xiàng)目,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01
  • SpringBoot 如何整合 ES 實(shí)現(xiàn) CRUD 操作

    SpringBoot 如何整合 ES 實(shí)現(xiàn) CRUD 操作

    這篇文章主要介紹了SpringBoot 如何整合 ES 實(shí)現(xiàn) CRUD 操作,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下
    2020-10-10
  • @RequestBody 部分屬性沒(méi)有轉(zhuǎn)化成功的處理

    @RequestBody 部分屬性沒(méi)有轉(zhuǎn)化成功的處理

    這篇文章主要介紹了@RequestBody 部分屬性沒(méi)有轉(zhuǎn)化成功的處理方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Java sleep方法及中斷方式、yield方法代碼實(shí)例

    Java sleep方法及中斷方式、yield方法代碼實(shí)例

    這篇文章主要介紹了Java sleep方法及中斷方式、yield方法代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • Spring?Boot?中的?@HystrixCommand?注解原理及使用方法

    Spring?Boot?中的?@HystrixCommand?注解原理及使用方法

    通過(guò)使用 @HystrixCommand 注解,我們可以輕松地實(shí)現(xiàn)對(duì)方法的隔離和監(jiān)控,從而提高系統(tǒng)的可靠性和穩(wěn)定性,本文介紹了Spring Boot 中的@HystrixCommand注解是什么,其原理以及如何使用,感興趣的朋友跟隨小編一起看看吧
    2023-07-07
  • Java生成范圍內(nèi)隨機(jī)整數(shù)的三種方法

    Java生成范圍內(nèi)隨機(jī)整數(shù)的三種方法

    在Java中生成隨機(jī)數(shù)的場(chǎng)景有很多,下面這篇文章主要給大家介紹了關(guān)于Java生成范圍內(nèi)隨機(jī)整數(shù)的三種方法,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • 深入剖析Java ReentrantLock的源碼

    深入剖析Java ReentrantLock的源碼

    ReentrantLock和Synchronized都是Java開(kāi)發(fā)中最常用的鎖,與Synchronized這種JVM內(nèi)置鎖不同的是,ReentrantLock提供了更豐富的語(yǔ)義。本文就來(lái)深入剖析一下ReentrantLock源碼,需要的可以參考一下
    2022-11-11
  • Java Map常用方法和實(shí)現(xiàn)類(lèi)的核心原理

    Java Map常用方法和實(shí)現(xiàn)類(lèi)的核心原理

    在Java集合框架中,Map是最核心、最常用的數(shù)據(jù)結(jié)構(gòu)之一,本文將從Map接口的設(shè)計(jì)哲學(xué)出發(fā),深入剖析HashMap、LinkedHashMap、TreeMap、Hashtable、ConcurrentHashMap等主要實(shí)現(xiàn)類(lèi)的底層原理、源碼實(shí)現(xiàn)、性能特性,感興趣的朋友跟隨小編一起看看吧
    2026-02-02

最新評(píng)論

乐都县| 武清区| 闽侯县| 铅山县| 南江县| 建始县| 崇义县| 开鲁县| 五大连池市| 荆门市| 公主岭市| 兰溪市| 大埔区| 仁布县| 辉县市| 海伦市| 修文县| 屯门区| 隆化县| 滨州市| 江津市| 孟连| 彰武县| 曲阳县| 都昌县| 蓬安县| 乌拉特后旗| 广州市| 洛隆县| 福海县| 策勒县| 夏河县| 江华| 二手房| 冀州市| 呼图壁县| 沈阳市| 浑源县| 保德县| 改则县| 龙海市|