springsecurity扩展session中存放的User对象

springsecurity扩展session中存放的User对象

参考文章
http://www.family168.com/oa/springsecurity/html/ch208-extenduser.html

在原来的mini-web的基础上,参考原来的配置:
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="plaintext" />
</authentication-provider>
<beans:bean id="userDetailsService" class="org.springside.examples.miniweb.service.security.UserDetailServiceImpl" />

这个配置基本上没有改变,只是重新查看了一下UserDetailServiceImpl.java里面的代码
原来的用户信息是实现的springsecurity的接口
org.springframework.security.userdetails.UserDetails
实现类为
org.springframework.security.userdetails.User
只放了username,password,权限列表等信息在session中,我们的扩展是要将user的主键ID放在session中,扩展User对象如下:
package org.springside.examples.miniweb.entity.user;
import org.springframework.security.GrantedAuthority;
/**
* 用户类扩展,将id存入session
* @author sillycat
*/
public class CustomerUserDetails extends
   org.springframework.security.userdetails.User {
private static final long serialVersionUID = -25559580612205393L;
private Long id;
public CustomerUserDetails(Long id, String username, String password,
    boolean enabled, boolean accountNonExpired,
    boolean credentialsNonExpired, boolean accountNonLocked,
    GrantedAuthority[] authorities) {
   super(username, password, enabled, accountNonExpired,
     credentialsNonExpired, accountNonLocked, authorities);
   this.id = id;
}
public Long getId() {
   return this.id;
}
public void setId(Long id) {
   this.id = id;
}
}
原来的UserDetailServiceImpl.java修改如下:
public UserDetails loadUserByUsername(String userName)
   throws UsernameNotFoundException, DataAccessException {
User user = userManager.getUserByLoginName(userName);
if (user == null)
   throw new UsernameNotFoundException(userName + " 不存在");
List<GrantedAuthority> authsList = new ArrayList<GrantedAuthority>();
for (Role role : user.getRoles()) {
   for (Authority authority : role.getAuths()) {
    authsList.add(new GrantedAuthorityImpl(authority.getName()));
   }
}
//没有扩展时候的处理代码,注释掉了
// org.springframework.security.userdetails.User userdetail = new
// org.springframework.security.userdetails.User(
// user.getLoginName(), user.getPassword(), true, true, true, true,
// authsList
// .toArray(new GrantedAuthority[authsList.size()]));
//调用扩展后的CustomerUserDetails,这样就将id属性扩展并交给springsecurity存放到session了
CustomerUserDetails userdetail = new CustomerUserDetails(user.getId(),
    user.getLoginName(), user.getPassword(), true, true, true,
    true, authsList.toArray(new GrantedAuthority[authsList.size()]));
return userdetail;
}
我们在jsp页面中这样查看一下:
<div>登陆用户信息: <br/>
ID: <security:authentication property="principal.id"/><br/>
NAME:<security:authentication property="principal.username"/><br/>
PWD:<security:authentication property="principal.password"/><br/>
</div>
就可以看到,我们扩展的id和username,password一起显示出来了。

你可能感兴趣的:(html,jsp,Web,Security)