- SecurityContextHolder叫编、SecurityContext and Authentication Objects
- UserDetailsService
- GrantedAuthority
SecurityContextHolder、SecurityContext、Authentication
SecurityContextHolder是最基礎(chǔ)的核心組件魂角,它內(nèi)部存儲著當(dāng)前用戶的基本信息粱甫。默認情況下拙已,使用ThreadLocal來保存這些信息冲粤。
獲取當(dāng)前用戶信息
Spring Security在SecurityContextHolder中存儲當(dāng)前用戶的信息(Authentication對象),獲取當(dāng)前用戶信息也就是要獲取Authentication對象爪瓜,在應(yīng)用的任何地方蹬跃,都可以使用如下代碼獲取當(dāng)前用戶名:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
UserDetailsService
- 從上述代碼中,我們知道铆铆,可以從Authentication獲取用戶信息蝶缀,用戶其實就是一個Object丹喻,它可以被強制轉(zhuǎn)換為UserDetails。
- UserDetails是Spring Security的一個核心接口翁都,他能代表一個當(dāng)前用戶碍论。
- 可以將UserDetails當(dāng)作是從數(shù)據(jù)庫中的用戶表到SecurityContextHolder中的用戶信息的一個適配接口。
那么柄慰,我們?nèi)绾螢镾pring Security提供UserDetails信息鳍悠?
答案是實現(xiàn)UserDetailsService接口。接口函數(shù):UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
GrantedAuthority
除了用戶信息坐搔,Authentication還可提供權(quán)限信息(使用GrantedAuthority來描述)藏研,使用getAuthorities()
函數(shù)獲取GrantedAuthority對象。
總結(jié)
- SecurityContextHolder:從SecurityContextHolder可獲取SecurityContext薯蝎。
- SecurityContext:包含Authentication信息。
- Authentication:包含用戶和權(quán)限信息谤绳。
- GrantedAuthority:包含權(quán)限信息占锯。
- UserDetails:包含用戶信息。
- UserDetailsService:用戶輸入賬號密碼后創(chuàng)建UserDetails缩筛。