嘗試自動裝配 SecurityContextHolder 我收到錯誤
required a bean of type 'org.springframework.security.core.context.SecurityContextHolder' that could not be found.
事實證明它可以從代碼的任何部分獲得,例如
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
為什么它不是一個 bean,它是如何在后臺初始化的?是否有其他類似的靜態實用程式類可從任何地方使用,我如何找到它們?
uj5u.com熱心網友回復:

這SecurityContextHolder是 Spring Security 存盤誰經過身份驗證的詳細資訊的地方。Spring Security 不關心
SecurityContextHolder是如何填充的。如果它包含一個值,則將其用作當前經過身份驗證的用戶。
...
因此,總而言之, 的主要目的SecurityContextHolder是管理SecurityContext. 安全背景關系旨在提供對用戶的Authentication.
Authentication代表當前經過身份驗證的用戶。并且由于Authentication是一個 Bean,它可以通過在另一個 Bean 中的依賴注入來提供,例如作為方法引數。
讓我們看一個例子。假設我們有一個控制器,它有一個端點回傳一個實體,Foo該實體需要來自以下方面的一些用戶資訊Authentication:
@RestController
public class FooController {
@GetMapping("/foo")
Foo getFoo(Authentication a) {
return FooUtils.generateFoo(a);
}
}
它generateFoo()通過傳遞Authentication注入的引數來使用該方法。generateFoo()位于其中的方法FooUtils是一個實用程式類。
public class FooUtils {
public static Foo generateFoo(Authentication a) {
return new Foo(a.getPrincipal());
}
}
Authentication不能在 的方法中注入FooUtils,因為它不是 Bean,因此它是由呼叫者分發的。如果我們想象呼叫鏈會更長,即在呼叫端點方法之間會有更多操作,并且在不使用它的幾個方法FooUtils.generateFoo()之間傳遞將不會很方便。Authentication
相反,可以使用并立即SecurityContextHolder獲取:AuthenticationFooUtils
public class FooUtils {
public static Foo generateFoo() {
Authentication a = SecurityContextHolder
.getContext()
.getAuthentication();
return new Foo(a.getPrincipal());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/536492.html
