一、擷取使用者資訊的兩種方式

二、重點講解使用Java方式擷取使用者資訊,講解其核心元件
核心元件:
1 定義
- 稱為shared的元件,是指它在架構中占有很重要的位置,架構離開它無法運作。
- 内置的一系列的過濾器中都用到了這些共享元件。
- 這些Java類表達了維持系統的建構代碼塊。
1 SecurityContextHolder
- 最基礎的對象,目前應用程式的目前安全環境的細節存儲在其中。
- 預設情況下,SecurityContextHolder使用ThreadLocal存儲這些資訊,如此意味着安全環境在同一個線程執行的方法一直是有效的。
- 我們把安全主體和系統互動的資訊都儲存在SecurityContextHolder中。
private static SecurityContextHolderStrategy strategy; public static SecurityContext getContext() { return strategy.getContext(); }
2 SecurityContext
- 上下文細節,以接口的形勢表示。
public interface SecurityContext extends Serializable { Authentication getAuthentication(); void setAuthentication(Authentication var1); }
- 其實作類為SecurityContextImpl
3 Authentication
- 在認證請求時用到是一個接口。我們把安全主體和系統互動的資訊都儲存在SecurityContextHolder 中了。 Spring Security 使用一個 Authentication 對應來表現這些 信 息 。 雖 然 你 通 常 不 需 要 自 己 創 建 一 個 Authentication 對 象 , 直 接 通 過SecurityContextHolder 擷取上下文對象,然後通過上下文對象(SecurityContext)擷取即可.引用《Pro Spring Security》中的一段話,An Authentication object is used both when an authentication request is created (when a user logs in),to carry around the different layers and classes of the framework the requesting data, and then when it is validated,containing the authenticated entity and storing it in SecurityContext.The most common behavior is that when you log in to the application a new Authentication object will be created storing your user name, password, and permissions—most of which are technically known as Principal, Credentials, and Authorities, respectively.翻譯過來就是說,在建立身份驗證請求(使用者登入時)時,将使用一個Authentication對象,以攜帶請求資料的架構的不同層和類,然後在驗證資料時将其包含驗證的實體并将其存儲在SecurityContext中。最常見的行為是,當您登入到應用程式時,将建立一個新的身份驗證對象(Authentication)存儲您的使用者名,密碼和權限-在技術上大多數依次稱為Principal(主體,即使用者),Credentials(憑證)和 Authorities(權限)
4 UserDetails
- UserDetails 是一個 Spring Security 的核心接口。 它代表一個主體(包含于使用者相關的資訊)。
在 Authentication 接口中有一個方法 Object getPrincipal(); 這個方法傳回的是一個 安全主題,大多數情況下,這個對象可以強制轉換成 UserDetails 對象,擷取到 UerDetails 對象之後,就可以通過這個對象的 getUserName()方法擷取目前使用者名。
- 我們可以定義類實作這個接口,儲存我們想要的資訊,并把它儲存在Authentication中。
三、 流程
SecurityContextHolder通過SecurityContextHolderStrategy的三個實作類中的一個來儲存SecurityContext(即上下文),也就是Authentication(認證資訊),
使用者認證資訊包括但不限于:
- 使用者權限集合
- 使用者名、密碼
-
是否已認證成功
...等
,通過getContext()擷取。