Spring Security如何基于Authentication獲取用戶信息
Spring Security使用一個Authentication對象來描述當(dāng)前用戶的相關(guān)信息。SecurityContextHolder中持有的是當(dāng)前用戶的SecurityContext,而SecurityContext持有的是代表當(dāng)前用戶相關(guān)信息的Authentication的引用。
這個Authentication對象不需要我們自己去創(chuàng)建,在與系統(tǒng)交互的過程中,Spring Security會自動為我們創(chuàng)建相應(yīng)的Authentication對象,然后賦值給當(dāng)前的SecurityContext。
但是往往我們需要在程序中獲取當(dāng)前用戶的相關(guān)信息,比如最常見的是獲取當(dāng)前登錄用戶的用戶名。在程序的任何地方,通過如下方式我們可以獲取到當(dāng)前用戶的用戶名。
public String getCurrentUsername() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } if (principal instanceof Principal) { return ((Principal) principal).getName(); } return String.valueOf(principal); }
通過Authentication.getPrincipal()可以獲取到代表當(dāng)前用戶的信息,這個對象通常是UserDetails的實(shí)例。獲取當(dāng)前用戶的用戶名是一種比較常見的需求,關(guān)于上述代碼其實(shí)Spring Security在Authentication中的實(shí)現(xiàn)類中已經(jīng)為我們做了相關(guān)實(shí)現(xiàn),所以獲取當(dāng)前用戶的用戶名最簡單的方式應(yīng)當(dāng)如下。
public String getCurrentUsername() { return SecurityContextHolder.getContext().getAuthentication().getName(); }
此外,調(diào)用SecurityContextHolder.getContext()獲取SecurityContext時,如果對應(yīng)的SecurityContext不存在,則Spring Security將為我們建立一個空的SecurityContext并進(jìn)行返回。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 基于android studio的layout的xml文件的創(chuàng)建方式2. 解決Android studio xml界面無法預(yù)覽問題3. 詳解Android studio 動態(tài)fragment的用法4. 圖文詳解vue中proto文件的函數(shù)調(diào)用5. 什么是python的自省6. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)7. Android如何加載Base64編碼格式圖片8. 使用Android studio查看Kotlin的字節(jié)碼教程9. Vuex localStorage的具體使用10. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)

網(wǎng)公網(wǎng)安備