最近2018中文字幕在日韩欧美国产成人片_国产日韩精品一区二区在线_在线观看成年美女黄网色视频_国产精品一区三区五区_国产精彩刺激乱对白_看黄色黄大色黄片免费_人人超碰自拍cao_国产高清av在线_亚洲精品电影av_日韩美女尤物视频网站

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
SpringSecurity如何基于Authentication獲取用戶信息

Spring Security使用一個(gè)Authentication對象來描述當(dāng)前用戶的相關(guān)信息。SecurityContextHolder中持有的是當(dāng)前用戶的SecurityContext,而SecurityContext持有的是代表當(dāng)前用戶相關(guān)信息的Authentication的引用。

創(chuàng)新互聯(lián)是一家專業(yè)提供嘉陵企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、H5開發(fā)、小程序制作等業(yè)務(wù)。10年已為嘉陵眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進(jìn)行中。

這個(gè)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)前用戶的信息,這個(gè)對象通常是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時(shí),如果對應(yīng)的SecurityContext不存在,則Spring Security將為我們建立一個(gè)空的SecurityContext并進(jìn)行返回。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。


分享文章:SpringSecurity如何基于Authentication獲取用戶信息
文章來源:http://fisionsoft.com.cn/article/jdosci.html