SpringSecurity的簡單認識

一、獲取用戶信息的兩種方式

image

二、重點講解使用Java方式獲取用戶信息,講解其核心組件

#核心組件:

1 定義

  1. 稱爲shared的組件,是指它在框架中佔有很重要的位置,框架離開它無法運行。
  2. 內置的一系列的過濾器中都用到了這些共享組件。
  3. 這些Java類表達了維持系統的構建代碼塊。

1 SecurityContextHolder

  1. 最基礎的對象,當前應用程序的當前安全環境的細節存儲在其中。
  2. 默認情況下,SecurityContextHolder使用ThreadLocal存儲這些信息,如此意味着安全環境在同一個線程執行的方法一直是有效的。
  3. 我們把安全主體和系統交互的信息都保存在SecurityContextHolder中。
           private static SecurityContextHolderStrategy strategy;
           public static SecurityContext getContext() {
               return strategy.getContext();
           }
    
    

2 SecurityContext

  1. 上下文細節,以接口的形勢表示。
        public interface SecurityContext extends Serializable {
            Authentication getAuthentication();
            void setAuthentication(Authentication var1);
        }
    
  2. 其實現類爲SecurityContextImpl

3 Authentication

  1. 在認證請求時用到是一個接口。我們把安全主體和系統交互的信息都保存在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

  1. UserDetails 是一個 Spring Security 的核心接口。 它代表一個主體(包含於用戶相關的信息)。
    在 Authentication 接口中有一個方法 Object getPrincipal(); 這個方法返回的是一個
    安全主題,大多數情況下,這個對象可以強制轉換成 UserDetails 對象,獲取到
    UerDetails 對象之後,就可以通過這個對象的 getUserName()方法獲取當前用戶名。
  2. 我們可以定義類實現這個接口,保存我們想要的信息,並把它保存在Authentication中。

三、 流程

SecurityContextHolder通過SecurityContextHolderStrategy的三個實現類中的一個來保存SecurityContext(即上下文),也就是Authentication(認證信息),
用戶認證信息包括但不限於:

  1. 用戶權限集合
  2. 用戶名、密碼
  3. 是否已認證成功
    …等
    ,通過getContext()獲取。

四、案例地址,簡單的demo

Spring.security案例地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章