(转)SpringSecurity扩展User类,获取Session
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_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]}
存的是登录成功时候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}
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?
${session.SPRING_SECURITY_CONTEXT.authentication.principal.username}
===================================== 分割线 ======================================
根据以上内容,在扩展了自己的user之后,可以在自己的Thymeleaf下面做一些事情了。
admin
(转)SpringSecurity扩展User类,获取Session的更多相关文章
- 一个简单的C#获取Session、设置Session类文件
一个简单的C#获取Session.设置Session类文件,本类主要实现大家最常用的两个功能: 1.GetSession(string name)根据session名获取session对象: 2.Se ...
- asp.net 类库中获取session c#类中获取session
asp.net 类库中获取session c#类中获取session 1. 先引入命名空间 using System.Web; using System.Web.SessionState; 在使用H ...
- 教你在Java的普通类中轻松获取Session以及request中保存的值
曾经有多少人因为不知如何在业务类中获取自己在Action或页面上保存在Session中值,当然也包括我,但是本人已经学到一种办法可以解决这个问题,来分享下,希望对你有多多少少的帮助! 如何在Java的 ...
- spring 普通类获取四大作用域request、applicationContext、session、page
几乎所有web应用容器都提供了四种类似Map的结构:application session request page,Jsp或者Servlet通过向着这四个对象放入数据,从而实现Jsp和Servlet ...
- SQLServer中使用扩展事件获取Session级别的等待信息以及SQLServer 2016中Session级别等待信息的增强
本文出处:http://www.cnblogs.com/wy123/p/6835939.html 什么是等待 简单说明一下什么是等待:当应用程序对SQL Server发起一个Session请求的时候, ...
- spring的普通类中获取session和request对像
在使用spring时,经常需要在普通类中获取session,request等对像. 1.第一钟方式,针对Spring和Struts2集成的项目: 在有使用struts2时,因为struts2有一个接口 ...
- jeecg中的一个上下文工具类获取request,session
通过调用其中的方法可以获取到request和session,调用方式如下: HttpServletRequest request = ContextHolderUtils.getRequest();H ...
- SpringBoot 封装返回类以及session 添加获取
1.创建返回类Result public class Result<T>{ /*错误码*/ private Integer code; /*提示信息 */ private String m ...
- spring在普通类中获取session和request
在使用spring时,经常需要在普通类中获取session,request等对像.比如一些AOP拦截器类,在有使用struts2时,因为struts2有一个接口使用org.apache.struts2 ...
随机推荐
- TJI读书笔记13-内部类
TJI读书笔记13-内部类 TJI读书笔记13-内部类 创建内部类 内部类和外部类的关系 .this和.new 内部类和向上转型 局部内部类 匿名内部类 匿名内部类的定义和初始化 使用匿名内部类来实现 ...
- DataTable.Compute()用法
DataTable.Compute()用法 2010-04-07 11:28 一.DataTable.Compute()方法說明如下 作用: 计算用来传递筛选条件的当前行上的给定表达 ...
- SilverLight - Memory Leak
There is a memory leak issue in current silverlight project. It occurs in the search function: the m ...
- 通过反射向将EF的实体映射配置加入到实体模型中
public AdminDbContext() : base("MemberDbContext") { //不使用代理创建导航属性,避免WCF序列化错误 Configuration ...
- html() 和 text() 方法的区别
html()方法仅支持XHTML的文档,不能用于XML文档,而text()既支持HTML文档,也 支持XML文档. html():没有参数,用于获取html的值: html(val):有参数,用于设置 ...
- 利用Maven建立java web项目
方法一:在IntelliJ IDEA中创建maven web项目 一.在新建项目对话框中,选择“Maven”类型,设置好jdk,勾选“create from archetype”,在列表中选择“mav ...
- js 验证码 倒计时60秒
js 验证码 倒计时60秒 <input type="button" id="btn" value="免费获取验证码" /> & ...
- VS调试在Win7(vista系列)操作系统下 HttpListener拒绝访问解决办法
一. VS调试在Win7(vista系列)操作系统下 HttpListener无法绑定多个 指定IP.端口问题 来自:http://www.cnblogs.com/ryhan/p/4195693.ht ...
- K.O. ----- bat文件的中文乱码
-------siwuxie095 bat文件在保存时如果没有选择正确的格式,中文部分就会出现乱码 1.记事本 用记事本编写如下代码: 另存为:测试.bat,编码设置为:UTF-8,就会 ...
- codeforces 732/D 二分
给出考试时间和考试需要准备的时间,问最早考完所有科目的时间 二分答案 NlogN 二分抄神犇的写法 感觉挺舒服的嘻嘻嘻 #include<bits/stdc++.h> using name ...