Spring Security如何基于Authentication獲取用戶信息
Spring Security使用一個(gè)Authentication對(duì)象來(lái)描述當(dāng)前用戶的相關(guān)信息。SecurityContextHolder中持有的是當(dāng)前用戶的SecurityContext,而SecurityContext持有的是代表當(dāng)前用戶相關(guān)信息的Authentication的引用。
這個(gè)Authentication對(duì)象不需要我們自己去創(chuàng)建,在與系統(tǒng)交互的過(guò)程中,Spring Security會(huì)自動(dòng)為我們創(chuàng)建相應(yīng)的Authentication對(duì)象,然后賦值給當(dāng)前的SecurityContext。
但是往往我們需要在程序中獲取當(dāng)前用戶的相關(guān)信息,比如最常見的是獲取當(dāng)前登錄用戶的用戶名。在程序的任何地方,通過(guò)如下方式我們可以獲取到當(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); }
通過(guò)Authentication.getPrincipal()可以獲取到代表當(dāng)前用戶的信息,這個(gè)對(duì)象通常是UserDetails的實(shí)例。獲取當(dāng)前用戶的用戶名是一種比較常見的需求,關(guān)于上述代碼其實(shí)Spring Security在Authentication中的實(shí)現(xiàn)類中已經(jīng)為我們做了相關(guān)實(shí)現(xiàn),所以獲取當(dāng)前用戶的用戶名最簡(jiǎn)單的方式應(yīng)當(dāng)如下。
public String getCurrentUsername() { return SecurityContextHolder.getContext().getAuthentication().getName(); }
此外,調(diào)用SecurityContextHolder.getContext()獲取SecurityContext時(shí),如果對(duì)應(yīng)的SecurityContext不存在,則Spring Security將為我們建立一個(gè)空的SecurityContext并進(jìn)行返回。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 如何在jsp界面中插入圖片2. ASP實(shí)現(xiàn)加法驗(yàn)證碼3. python selenium 獲取接口數(shù)據(jù)的實(shí)現(xiàn)4. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)5. 詳解JSP 內(nèi)置對(duì)象request常見用法6. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算7. Python matplotlib 繪制雙Y軸曲線圖的示例代碼8. jsp EL表達(dá)式詳解9. JSP servlet實(shí)現(xiàn)文件上傳下載和刪除10. springboot集成與使用Sentinel的方法
