Spring Boot Security Core

依賴配置(Maven)

xml

復制

下載

運行

<!-- Spring Security Core -->
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-core</artifactId><version>6.2.5</version> <!-- 使用最新版本 -->
</dependency><!-- 如果使用Web安全 -->
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-web</artifactId><version>6.2.5</version>
</dependency><!-- 如果使用配置 -->
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId><version>6.2.5</version>
</dependency>

要正確實現?getCurrentUserId()?方法,需要導入以下 Spring Security 相關的包:

java

復制

下載

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

完整代碼示例

java

復制

下載

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;public class SecurityUtils {/*** 獲取當前用戶ID(需要根據實際認證系統實現)* * 此方法從Spring Security的SecurityContextHolder中獲取當前認證信息,* 并返回用戶名作為用戶ID。如果用戶未認證,返回"ANONYMOUS"。* * @return 當前用戶ID或"ANONYMOUS"*/public static String getCurrentUserId() {// 從SecurityContextHolder獲取認證信息Authentication authentication = SecurityContextHolder.getContext().getAuthentication();if (authentication != null && authentication.isAuthenticated()) {// 返回用戶名(可根據需要調整為其他用戶標識)return authentication.getName();}return "ANONYMOUS";}
}

關鍵類說明

  1. SecurityContextHolder

    • 位置:org.springframework.security.core.context.SecurityContextHolder

    • 作用:Spring Security 的安全上下文容器,存儲當前線程的安全信息

    • 核心方法:getContext()?獲取當前安全上下文

  2. Authentication

    • 位置:org.springframework.security.core.Authentication

    • 作用:表示用戶認證信息的接口

    • 核心方法:

      • getName():獲取用戶名(通常是用戶ID)

      • isAuthenticated():檢查用戶是否已認證

      • getPrincipal():獲取用戶主體(可能是用戶名或UserDetails對象)

      • getAuthorities():獲取用戶權限

實際項目中的增強實現

在真實項目中,您可能需要更完整的實現:

java

復制

下載

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;public class SecurityUtils {/*** 獲取當前用戶ID*/public static String getCurrentUserId() {Authentication authentication = getAuthentication();if (authentication != null && authentication.isAuthenticated()) {Object principal = authentication.getPrincipal();// 處理不同類型的Principalif (principal instanceof UserDetails) {return ((UserDetails) principal).getUsername();} else if (principal instanceof String) {return (String) principal;} else if (principal instanceof CustomUser) { // 自定義用戶對象return ((CustomUser) principal).getUserId();}}return "ANONYMOUS";}/*** 獲取當前用戶詳細信息*/public static UserDetails getCurrentUserDetails() {Authentication authentication = getAuthentication();if (authentication != null && authentication.isAuthenticated() &&authentication.getPrincipal() instanceof UserDetails) {return (UserDetails) authentication.getPrincipal();}return null;}/*** 檢查用戶是否具有特定角色*/public static boolean hasRole(String role) {Authentication authentication = getAuthentication();return authentication != null && authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_" + role));}/*** 安全獲取Authentication對象*/private static Authentication getAuthentication() {try {return SecurityContextHolder.getContext().getAuthentication();} catch (Exception e) {// 處理非Web環境或安全上下文未初始化的情況return null;}}
}

使用場景示例

java

復制

下載

@RestController
@RequestMapping("/api/user")
public class UserController {@GetMapping("/profile")public ResponseEntity<UserProfile> getUserProfile() {String userId = SecurityUtils.getCurrentUserId();// 防止匿名訪問if ("ANONYMOUS".equals(userId)) {return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();}UserProfile profile = userService.getProfile(userId);return ResponseEntity.ok(profile);}@PreAuthorize("hasRole('ADMIN')")@GetMapping("/admin")public ResponseEntity<String> adminOnly() {return ResponseEntity.ok("管理員專屬內容");}
}

常見問題解決方案

  1. 返回 null 而不是用戶名

    java

    復制

    下載

    // 使用 getPrincipal() 替代 getName()
    Object principal = authentication.getPrincipal();
    if (principal instanceof UserDetails) {return ((UserDetails) principal).getUsername();
    } else if (principal instanceof String) {return (String) principal;
    }
  2. 匿名用戶處理

    java

    復制

    下載

    // 檢查匿名用戶
    if (authentication instanceof AnonymousAuthenticationToken) {return "ANONYMOUS";
    }
  3. 自定義用戶ID

    java

    復制

    下載

    // 實現自定義UserDetails
    public class CustomUserDetails implements UserDetails {private String userId; // 使用用戶ID代替用戶名// 其他實現...@Overridepublic String getUsername() {return userId; // 返回用戶ID}
    }
  4. JWT 集成

    java

    復制

    下載

    // 在JWT認證中獲取用戶ID
    public class JwtAuthenticationFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {String token = getToken(request);if (token != null && jwtUtil.validateToken(token)) {String userId = jwtUtil.getUserIdFromToken(token);// 創建認證信息UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userId, null, authorities);SecurityContextHolder.getContext().setAuthentication(auth);}chain.doFilter(request, response);}
    }

總結

核心導入包:

java

復制

下載

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

在 Spring Security 環境中,SecurityContextHolder?是獲取當前用戶信息的標準方式:

  1. 通過?getAuthentication()?獲取認證信息

  2. 通過?getName()?或?getPrincipal()?獲取用戶標識

  3. 檢查?isAuthenticated()?確保用戶已認證

  4. 處理匿名用戶情況

在實際項目中,通常會創建?SecurityUtils?工具類封裝這些安全相關操作,提高代碼復用性和可維護性。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/86226.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/86226.shtml
英文地址,請注明出處:http://en.pswp.cn/web/86226.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【趙渝強老師】OceanBase云平臺OCP

OCP的全稱是OceanBase Cloud Platform&#xff0c;即&#xff1a;OceanBase云平臺。OCP面向有OceanBase管理需求的中小型用戶&#xff0c;提供了基礎的主機管理、OceanBase 集群和租戶運維等能力。在OCP中主要包含兩個組成部分&#xff0c;它們分別是&#xff1a;MetaDB和OCP S…

快速定位Swagger文檔請求地址‘/v2/api-docs‘,發生未知異常.NullPointerException:精準定位+根治方案

問題現場&#xff1a;訪問 http://localhost:8080/v2/api-docs 時日志報錯&#xff1a; 請求地址/v2/api-docs,發生未知異常. java.lang.NullPointerException: nullat springfox.documentation.swagger2.mappers.RequestParameterMapper.bodyParameter(RequestParameterMappe…

圖像處理解決方案

證件照小工具微信小程序系統是基于微擎開源生態開發的多功能圖像處理平臺&#xff0c;專為用戶提供便捷的證件照制作及圖片編輯服務。微擎系統作為一款基于 PHP 開發的開源應用生態系統&#xff0c;具備快速搭建多端應用的能力&#xff0c;其模塊化架構與跨平臺兼容性為證件照工…

Qt聯合Halcon開發四:【詳細圖解】海康相機配置并鏈接測試

1. 下載與安裝海康 MVS SDK 首先&#xff0c;訪問海康機器人官網的下載中心&#xff0c;選擇 “Machine Vision” 模塊下的 MVS 軟件包。 1. 打開瀏覽器&#xff0c;進入&#xff1a;https://www.hikrobotics.com/cn/ 2. 下載最新版的 MVS 安裝包&#xff08;通常以 MVS_x.x.…

vue3打包后,圖片丟失

前言&#xff1a; 在 webpack 中使用 require() 來引入靜態圖片&#xff0c;但在 vite 中就不行。 代碼實現 <template><div><img :src"empty"></div> </template><script setup> // 引入本地圖片(注意改成您的路徑) import em…

MongoDB 8.0.10 windows11安裝記錄

最近在學習node&#xff0c;看的教程用的是MongoDB 5.0的&#xff0c;安裝上和新版的有一些區別&#xff0c;都安裝完后不能直接在C:\Program Files\MongoDB\Server\8.0\bin 這個目錄使用mongo 啟動&#xff0c;因為都沒那文件。 摸索了下弄好了。 下載社區版最新安裝包&#…

信息系統項目管理師023:云計算(2信息技術發展,網絡安全面試問題

2.關鍵技術 云計算的關鍵技術主要涉及虛擬化技術、云存儲技術、多租戶和訪問控制管理、云安全技術等。 1&#xff09;虛擬化技術 虛擬化是一個廣義術語&#xff0c;在計算機領域通常是指計算元件在虛擬的基礎上而不是真實的基礎上運行。虛擬化技術可以擴大硬件的容量&#x…

django csrf的局限性

Django的CSRF保護機制雖被廣泛應用&#xff0c;但在實際場景中存在以下關鍵局限性&#xff0c;需開發者特別注意&#xff1a; 一、內容類型限制&#xff08;Content-Type約束&#xff09; 僅保護特定響應類型 CSRF中間件默認只對text/html和application/xmlxhtml響應生效&#…

如何將緩存存到客戶端瀏覽器上呢

要將緩存存到客戶端瀏覽器&#xff0c;關鍵是讓 瀏覽器接收到合適的 HTTP 緩存控制響應頭。這通常通過 add_header 添加控制頭來實現。 ? 一般做法&#xff08;強緩存 協商緩存&#xff09;&#xff1a; &#x1f539; 1. 強緩存&#xff1a;使用 Cache-Control 和 Expires …

微軟ASR與開源模型分析

一、微軟ASR核心能力 1. 支持場景 場景功能實時語音轉文本低延遲流式識別&#xff08;會議字幕/直播轉錄&#xff09;音頻文件轉文本支持多種格式&#xff08;WAV/MP3等&#xff09;&#xff0c;批量處理長音頻定制化模型針對特定行業術語&#xff08;醫療/金融&#xff09;訓…

2025下半年軟考中級科目難度解析與選科指南

2025年下半年軟考中級科目共有6科&#xff0c;包括系統集成項目管理工程師、信息系統管理工程師、信息安全工程師、網絡工程師、軟件設計師以及多媒體應用設計師。面對眾多科目&#xff0c;考生應如何做出選擇&#xff1f; 一、考試時間安排 在開始備考之前&#xff0c;了解考…

深度剖析:PPP PRIVATE NETWORK UDP/IP AGGLIGATOR

&#x1f680; 深度剖析&#xff1a;PPP PRIVATE NETWORK UDP/IP AGGLIGATOR &#x1f3d7;? 一、架構概述 這是一個高性能網絡聚合系統&#xff0c;核心功能是通過多路TCP連接隧道化UDP流量&#xff0c;提升網絡傳輸的可靠性和性能。系統采用C編寫&#xff0c;基于Boost.Asi…

05-StarRocks功能使用FAQ

StarRocks功能使用FAQ 概述 本文檔整理了StarRocks功能使用過程中常見的問題和解決方案,涵蓋了表管理、分區、索引、物化視圖、外部表等核心功能的使用方法和最佳實踐。 表管理FAQ Q1: 如何創建和管理表? A: 表管理方法: 1. 創建表 -- 創建基本表 CREATE TABLE table…

ASP.NET Core API文檔與測試實戰指南

前言 在現代軟件開發中&#xff0c;API&#xff08;應用程序編程接口&#xff09;已成為不同服務和應用程序之間通信的橋梁。一個優秀的API不僅需要具備良好的功能性&#xff0c;更需要有完善的文檔和全面的測試策略。本文將深入探討ASP.NET Core環境下的API文檔生成與測試實踐…

域名 SSL證書和IP SSL證書有什么區別?

在互聯網安全領域&#xff0c;SSL證書扮演著至關重要的角色&#xff0c;它能夠有效保障數據傳輸的安全性&#xff0c;防止數據泄露和被篡改。而域名SSL證書與IP SSL證書作為兩種不同類型的SSL證書&#xff0c;各自有著獨特的特點和適用場景&#xff0c;本文國科云將對它們進行詳…

多個Vue項目共用一個node_modules依賴包,避免占用太大內存,window上創建微鏈接

最近突然發現電腦內存不夠了&#xff0c;沒辦法項目太多了&#xff0c;新加的項目也安裝不了依賴包&#xff0c;內存不夠了。 然后我最近發現個新東西&#xff0c;就是多個項目共用一個依賴包。 第一步&#xff1a; 可以創建一個空文件夾專門放依賴包&#xff0c;也可以直接用…

目標檢測新升級:用YOLOv8打造密度視頻熱力圖可視化

文章目錄 目標檢測新升級&#xff1a;用YOLOv8打造密度&視頻熱力圖可視化一、YOLOv8的改進&#xff08;一&#xff09;模型結構優化&#xff08;二&#xff09;注意力機制的引入 二、YOLOv8可視化熱力圖的原理與方法&#xff08;一&#xff09;熱力圖的基本概念&#xff08…

QT6 源(126)QModelIndex 模型索引:閱讀注釋與測試其成員函數,及其源代碼。以及 typedef QList<QModelIndex> QModelIndexList;

&#xff08;1&#xff09;模型里條目的索引是支持調試打印的 &#xff1a; &#xff08;2&#xff09;還結合上例的測試結果&#xff0c;給出本模型索引的定義&#xff0c;如下 &#xff1a; &#xff08;3&#xff09;繼續本模型索引類的成員函數的測試&#xff0c;還使用上面…

分布式環境下 Spring Boot 項目基于雪花算法的唯一 ID 生成方案

一、分布式系統 分布式系統是指將多個獨立的計算節點通過網絡連接&#xff0c;協同完成同一目標的系統架構。其核心特征是&#xff1a; 多個獨立節點&#xff1a;每個節點都是一個可獨立運行的服務實例網絡通信&#xff1a;節點間通過網絡協議&#xff08;如HTTP、RPC&#x…

如何在 Chrome 瀏覽器中保存從商店下載的擴展程序到本地

如何在 Chrome 瀏覽器中保存從商店下載的擴展程序到本地 方法一&#xff1a;通過擴展程序頁面直接導出&#xff08;適用于已安裝的擴展&#xff09; 打開 Chrome 擴展管理頁面 在地址欄輸入&#xff1a;chrome://extensions/或通過菜單&#xff1a;? > 更多工具 > 擴展…