(轉)SpringSecurity擴展User類,獲取Session

1.在session中取得spring security的登陸用戶名以下java

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

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

下面一段代碼主要描述的是session中的存的變量session

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

存的是登陸成功時候session中存的信息
session {SPRING_SECURITY_CONTEXT=org.springframework.security.context.SecurityContextImpl@87b16984: Authentication: org.springframework.security.providers.cas.CasAuthenticationToken@87b16984: Principal: com.avi.casExtends.UserInfo@ff631d80: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails@12afc: RemoteIpAddress: 127.0.0.1; SessionId: AE56E8925195DFF4C50ABD384574CCEA; Granted Authorities: ROLE_ADMIN Assertion: org.jasig.cas.client.validation.AssertionImpl@661a11 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]}ui

存的是登陸成功時候session中存的信息
session {SPRING_SECURITY_CONTEXT=org.springframework.security.context.SecurityContextImpl@87b16984: Authentication: org.springframework.security.providers.cas.CasAuthenticationToken@87b16984: Principal: com.avi.casExtends.UserInfo@ff631d80: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails@12afc: RemoteIpAddress: 127.0.0.1; SessionId: AE56E8925195DFF4C50ABD384574CCEA; Granted Authorities: ROLE_ADMIN Assertion: org.jasig.cas.client.validation.AssertionImpl@661a11 Credentials (Service/Proxy Ticket): ST-3-1lX3acgZ6HNgmhvjXuxB-cas, userId=2, userName=test}this

2.在頁面端用tag獲取code

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

或者接口

或者取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?






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

===================================== 分割線 ======================================
根據以上內容,在擴展了本身的user以後,能夠在本身的Thymeleaf下面作一些事情了。

admin

sucess
相關文章
相關標籤/搜索