1. 程式人生 > >Spring Security 取Session中的值和修改userDetails(轉)

Spring Security 取Session中的值和修改userDetails(轉)

1.在session中取得spring security的登入使用者名稱如下

${session.SPRING_SECURITY_CONTEXT.authentication.principal.username}

spring security 把SPRING_SECURITY_CONTEXT 放入了session 沒有直接把username 放進去。

下面一段程式碼主要描述的是session中的存的變數

view plaincopy to clipboardprint?
存跳轉時候的URL
session {SPRING_SECURITY_SAVED_REQUEST_KEY=SavedRequest[http://localhost:8080/AVerPortal/resourceAction/resourceIndex.action]}

存的是登入成功時候session中存的資訊
session {SPRING_SECURITY_C
[email protected]
87b16984: Authentication: or[email protected]87b16984: Principal: [email protected]: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Password: [PROTECTED]; Authenticated: true; Details:
[email protected]
: RemoteIpAddress: 127.0.0.1; SessionId: AE56E8925195DFF4C50ABD384574CCEA; Granted Authorities: ROLE_ADMIN Assertion: [email protected] Credentials (Service/Proxy Ticket): ST-3-1lX3acgZ6HNgmhvjXuxB-cas, userId=2, userName=test}
存跳轉時候的URL
session {SPRING_SECURITY_SAVED_REQUEST_KEY=SavedRequest[http://localhost:8080/AVerPortal/resourceAction/resourceIndex.action]}

存的是登入成功時候session中存的資訊
session {SPRING_SECURITY_C
[email protected]
87b16984: Authentication: or[email protected]87b16984: Principal: [email protected]: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Password: [PROTECTED]; Authenticated: true; Details: [email protected]: RemoteIpAddress: 127.0.0.1; SessionId: AE56E8925195DFF4C50ABD384574CCEA; Granted Authorities: ROLE_ADMIN Assertion: [email protected] Credentials (Service/Proxy Ticket): ST-3-1lX3acgZ6HNgmhvjXuxB-cas, userId=2, userName=test}

2.在頁面端用tag獲取

<%@ taglib prefix='security' uri='http://www.springframework.org/security/tags'%> 

<security:authentication property="principal.username"></security:authentication>

或者


<security:authorize ifAllGranted="ROLE_ADMIN">

<security:authentication property="principal.username"></security:authentication>

</security:authorize>


或者取session中的值

#session.SPRING_SECURITY_CONTEXT.authentication.principal.username等同於

3.在後臺獲取

UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
.getAuthentication()
.getPrincipal();


userDetails.getUsername()


想要獲取更多的資訊得擴充套件userDetails的預設實現類user類和UserDetailsService介面

由於springsecurity是把整個user資訊放入session中的即:session.SPRING_SECURITY_CONTEXT.authentication.principal

這個就是代表著user物件

因此我做了擴充套件增加user裡的資訊 加上userId

程式碼如下:擴充套件user


expand sourceview plaincopy to clipboardprint?
package com.avi.casExtends;

import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.User;

public class UserInfo extends User{
private static final long serialVersionUID = 1L;

private String userId;

@SuppressWarnings("deprecation")
public UserInfo(String username, String password, boolean enabled, GrantedAuthority[] authorities)
throws IllegalArgumentException {
super(username,password, enabled, authorities);
}

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public static long getSerialVersionUID() {
return serialVersionUID;
}


}
package com.avi.casExtends;

import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.User;

public class UserInfo extends User{
private static final long serialVersionUID = 1L;

private String userId;

@SuppressWarnings("deprecation")
public UserInfo(String username, String password, boolean enabled, GrantedAuthority[] authorities)
throws IllegalArgumentException {
super(username,password, enabled, authorities);
}

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public static long getSerialVersionUID() {
return serialVersionUID;
}


}


實現userDetailsservice介面

+ expand sourceview plaincopy to clipboardprint?
package com.avi.casExtends;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.avi.dao.AccountDao;
import com.avi.data.User;

public class UserInfoService implements UserDetailsService{

private AccountDao accountDao;
private Map<String, UserInfo> userMap = null;

public UserInfoService() {


}
public void fillMap(){
userMap = new HashMap<String, UserInfo>();
List<User> users = accountDao.findAllUsers();
UserInfo userInfo = null;
for(User user:users){
userInfo = new UserInfo(user.getUserName(),user.getPassword(),true,new GrantedAuthority[]{
new GrantedAuthorityImpl(user.getRole()),
});
userInfo.setUserId(user.getId().toString());

userMap.put(user.getUserName(), userInfo);
}
}

public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
if(userMap==null)
fillMap();
return userMap.get(username);
}

public AccountDao getAccountDao() {
return accountDao;
}

public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}

public Map<String, UserInfo> getUserMap() {
return userMap;
}

public void setUserMap(Map<String, UserInfo> userMap) {
this.userMap = userMap;
}

}
package com.avi.casExtends;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.avi.dao.AccountDao;
import com.avi.data.User;

public class UserInfoService implements UserDetailsService{

private AccountDao accountDao;
private Map<String, UserInfo> userMap = null;

public UserInfoService() {


}
public void fillMap(){
userMap = new HashMap<String, UserInfo>();
List<User> users = accountDao.findAllUsers();
UserInfo userInfo = null;
for(User user:users){
userInfo = new UserInfo(user.getUserName(),user.getPassword(),true,new GrantedAuthority[]{
new GrantedAuthorityImpl(user.getRole()),
});
userInfo.setUserId(user.getId().toString());

userMap.put(user.getUserName(), userInfo);
}
}

public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
if(userMap==null)
fillMap();
return userMap.get(username);
}

public AccountDao getAccountDao() {
return accountDao;
}

public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}

public Map<String, UserInfo> getUserMap() {
return userMap;
}

public void setUserMap(Map<String, UserInfo> userMap) {
this.userMap = userMap;
}

}


private AccountDao accountDao;是注入進來的查資料庫的類

然後修改XML檔案指定所要用到的service

+ expand sourceview plaincopy to clipboardprint?
<authentication-provider user-service-ref="userDetailsService"/>

<bean id="userDetailsService" class="com.avi.casExtends.UserInfoService" singleton="false">
<property name="accountDao" ref="accountDao"/>
</bean>
<authentication-provider user-service-ref="userDetailsService"/>

<bean id="userDetailsService" class="com.avi.casExtends.UserInfoService" singleton="false">
<property name="accountDao" ref="accountDao"/>
</bean>


${session.SPRING_SECURITY_CONTEXT.authentication.principal.username}

相關推薦

Spring Security Session修改userDetails()

1.在session中取得spring security的登入使用者名稱如下${session.SPRING_SECURITY_CONTEXT.authentication.principal.username}spring security 把SPRING_SECURITY

jssession

在js中貌似不能取session的值,我在後臺設定的session一直拿不到,於是用間接的方式拿到session的值。 首先在jsp中嵌入java程式碼,用java設定一個變數來取session值,再在頁面設定標籤取這個變數的值,最後通過js取標籤的值(即是session的

spring@value不到的幾種情況

spring@value取不到值的幾種情一,spring組件重寫構造方法,在構造方法中引用@value為null由於spring實例化順序為先執行構造方法,再註入成員變量,所以序為先執行構造方法,再註入成員變量,所以ing實例化順取值為null解決辦法為:再寫一個常量類,在常量類中引用@value,再在構造方

JS陣列相同的不同的

var arr1 = ["1", "2", "3"]; var arr2 = [1, "f", "g", 3]; var arr3 = []; for (var s in arr1) { for (v

讀取屬性修改

package com.chehaha.theme; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundExce

濾波演算法、均值濾波區別

濾波演算法:  這裡所講的演算法都是針對影象空間的濾波演算法,其中模板,可以理解為影象形態學中的結構元素,是用來選取影象中的那些畫素點被用來操作的。空間濾波根據其功能劃分為平滑濾波和銳化濾波。平滑濾波:能減弱或者消除影象中高頻率分量,但不影響低頻率分量,在實際應用中可用來消除噪聲。銳化濾波

Spring Security 梳理 - session

Spring Security預設的行為是每個登入成功的使用者會新建一個Session。這也就是下面的配置的效果: <http create-session="ifRequired">...</http> 這貌似沒有問題,但其實對大規模的網站是致命的。使用者越多,新建的s

在hibernate查詢資料的 sessionget load的區別:

* 第一點.傳送SQL的時機: * load這個方法採用了一個技術.lazy延遲載入(懶載入).真正使用這個物件的資料的時候.(物件的資料不包括主鍵). * get這個方法是立即檢索.當執行session.get()方法的時候,馬上傳送SQL語句查詢.   * 第二點.返回的物件:

使用zTree在form表單提交修改回顯

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <

SESSION增加刪除

   else         {          if(strUpgrade != null && !"".equals(strUpgrade)){           strUpgrade = strUpgrade.substring(0,strUpg

VS2015控制檯獲取修改當前字型大小(2-2)

2.2 GetConsoleFontSize()函式 GetConsoleFontSize()函式的作用是獲取指定控制檯輸出視窗字型的尺寸。 2.2.1 函式介紹 GetConsoleFontSize()函式的格式為 COORD WINAPI GetConsoleFontSize

編寫一個程式,對輸入的四個數最大最小

<span style="font-size:24px;">int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine());

學習Spring Security的過程遇到的問題彙總

首先分享兩個學習Spring security的資源:http://www.mossle.com/docs/auth/html/index.html   (寫成於2009年,較老,但是對於初學者還是很有幫助的) http://www.iteye.com/blogs/subj

spring security(八) session 併發,剔除前一個使用者

解決 session 併發問題 ,同時只有一個使用者線上。 有一個使用者線上後其他的裝置登入此使用者將剔除前一個使用者。強制前一個使用者下線。 1.修改security配置 新增 SessionRegistry,自己管理SessionRegistry

Matlab影象去噪(均值)

簡單概念 影象去噪是數字影象處理中的重要環節和步驟。去噪效果的好壞直接影響到後續的影象處理工作如影象分割、邊緣檢測等。影象訊號在產生、傳輸過程中都可能會受到噪聲的汙染,一般數字影象系統中的常見噪聲主要有:高斯噪聲(主要由阻性元器件內部產生)、椒鹽噪聲(主要是影

php 在同一個表單新增修改資料 二

好吧,其實我這人不看重訪問量的,但是今天一天的訪問量比我去年發的一篇還要多. 我還是有點小小的驚訝的.作為一個做技術的屌絲.不,我不認為自己是屌絲,我覺得程式設計是一件高大山的職業.雖然很累,但是確實能讓你每天的生活很充實. No matter whether you be

jsp頁面獲取session的方式

jsp頁面獲取session值 java程式碼 @RequestMapping(value = "/chkUser",method = RequestMethod.POST,produces

SessionremoveAttribute()invalidate()的區別?

用於清空指定的session: request.getSession().removeAttribute("globe_user");  用於清空當前會話的全部的session: request.ge

spring mvc $不到的問題

java程式碼如下ModelAndView view = new ModelAndView(); view.addObject("", 10); return "index";index.jsp取值:

演算法導論 學習筆記 第九章 順序統計

本章其實只講了一個問題,那就是如何從一個數組當中用線性時間內找出第i個小的元素。 最小值和最大值 這個就比較簡單了,直接挨個比,執行時間就是線性的,而且這就是最好的辦法。 如何同時找出最小值和最大值咧? 這個其實也簡單,那就記錄兩個資料唄。執行時間是找