Spring Security
基於 Spring 的權限管理框架,權限管理主要由身份認證Authentication
和權限管理Authorization
兩部分組成。身份認證負責對用戶進行身份鑑定,如驗證用戶名+口令的方式,鑑定的結果就是通過或者不通過。權限管理負責對用戶(準確的說是通過了身份認證的用戶)在系統內的權限提供支持,如管理員A允許訪問文件,管理員B不允許導出數據。
AuthenticationManager
public interface AuthenticationManager
Authentication authenticate(Authentication authentication) throws AuthencationException;
AuthenticationManager
是一個接口,定義了authenticate
方法,在系統中用來進行身份認證的方法:
- 返回 Authencition 表示認證成功
- 拋出 AuthenticationException 異常表示認證失敗
AuthenticationManager主要實現類是ProviderManager,ProviderManager中管理衆多AuthenticationProvider。因此,在一次完整的認證流程中,實際允許存在多個(種)認證,例如表單認證、用戶名密碼認證、指紋認證,每一個認證都是一個AuthenticationProvider,都由ProviderManager進行統一管理。
Authentication
Authentication保存認證以及認證成功的信息,其接口定義爲:
public interface Authentication extends Principal, Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
Object getCredentials();
Object getdetails();
Object getPrincipal();
Boolean isAuthenticated();
setAuthenticated();
}
- getAuthorities 獲取權限
- getCredentials 獲取憑證,如密碼
- getdetails 獲取用戶詳情
- getPrincipal 獲取用戶身份信息,如用戶名等
- isAuthenticated 用戶是否認證成功
SecurityContextHolder
Spring Security基於ThreadLocal管理,因此SecurityContextHolder是用來獲取Authentication的工具或者說方法。用戶登錄成功後,Spring Security將用戶信息保存到SecurityContextHolder,SecurityContextHolder通過ThreadLocal實現本次認證信息與當前請求線程綁定,不能被其它線程訪問。當請求結束,SecurityContextHolder將用戶信息放到Session保存,並清空SecurityContextHolder中的數據。下次請求來到時,SecurityContextHolder從Session中獲取用戶信息,請求結束時保存回Session並清空SecurityContextHolder。
AccessDecisionManager
AccessDecisionManager 訪問決策管理器,用來決定此次訪問是否被允許。需要AccessDecisionVoter配合。
AccessDecisionvoter
AccessDecisionVoter 訪問決策投票器,檢查用戶是否具備應有的角色,進而投出贊成、返回或棄權票。AccessDecisionManager和AccessDecisionvoter都有衆多實現類,AccessDecisionManager會挨個遍歷AccessDecisionvoter,進而決定是否允許用戶訪問。
ConfigAttribute
ConfigAttribute 用來保存授權時的角色信息。
bilibili - 編程不良人 - SpringSecurity最新實戰