扩展springsecurity的User类

package com.snda.swp.account.po;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;

//不可变类
public class UserInfo implements UserDetails, CredentialsContainer {

 private static final long serialVersionUID = 5997839307263494359L;

 // ~ Instance fields
 // ================================================================================================
 private String password;

 private String name;// 用户的中文姓名

 private String email;// 用户的邮箱地址

 private final String username;

 private final Set<GrantedAuthority> authorities;

 private final boolean accountNonExpired;

 private final boolean accountNonLocked;

 private final boolean credentialsNonExpired;

 private final boolean enabled;

 // ~ Constructors
 // ===================================================================================================
 public UserInfo(String password, String name, String email,
   final String username,
   final Collection<? extends GrantedAuthority> authorities,
   final boolean accountNonExpired, final boolean accountNonLocked,
   final boolean credentialsNonExpired, final boolean enabled) {
  if (username == null || "".equals(username) || password == null)
   throw new IllegalArgumentException(
     "Cannot pass null or empty values to constructor");
  this.password = password;
  this.name = name;
  this.email = email;
  this.username = username;
  this.accountNonExpired = accountNonExpired;
  this.accountNonLocked = accountNonLocked;
  this.credentialsNonExpired = credentialsNonExpired;
  this.enabled = enabled;
  this.authorities = Collections
    .unmodifiableSet(sortAuthorities(authorities));
 }

 // ~ Methods
 // ========================================================================================================
 public Collection<GrantedAuthority> getAuthorities() {
  return authorities;
 }

 public String getPassword() {
  return password;
 }

 public String getUsername() {
  return username;
 }

 public String getEmail() {
  return email;
 }

 public String getName() {
  return name;
 }

 public boolean isAccountNonExpired() {
  return accountNonExpired;
 }

 public boolean isAccountNonLocked() {
  return accountNonLocked;
 }

 public boolean isCredentialsNonExpired() {
  return credentialsNonExpired;
 }

 public boolean isEnabled() {
  return enabled;
 }

 public void eraseCredentials() {
  password = null;
 }

 private static SortedSet<GrantedAuthority> sortAuthorities(
   Collection<? extends GrantedAuthority> authorities) {
  Assert.notNull(authorities,
    "Cannot pass a null GrantedAuthority collection");
  // Ensure array iteration order is predictable (as per
  // UserDetails.getAuthorities() contract and SEC-717)
  SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<GrantedAuthority>(
    new AuthorityComparator());

  for (GrantedAuthority grantedAuthority : authorities) {
   Assert.notNull(grantedAuthority,
     "GrantedAuthority list cannot contain any null elements");
   sortedAuthorities.add(grantedAuthority);
  }

  return sortedAuthorities;
 }

 private static class AuthorityComparator implements
   Comparator<GrantedAuthority>, Serializable {
  public int compare(GrantedAuthority g1, GrantedAuthority g2) {
   // Neither should ever be null as each entry is checked before
   // adding it to the set.
   // If the authority is null, it is a custom authority and should
   // precede others.
   if (g2.getAuthority() == null) {
    return -1;
   }

   if (g1.getAuthority() == null) {
    return 1;
   }

   return g1.getAuthority().compareTo(g2.getAuthority());
  }
 }

 @Override
 public boolean equals(Object rhs) {
  if (rhs instanceof UserInfo)
   return username.equals(((UserInfo) rhs).username);
  return false;
 }

 @Override
 public int hashCode() {
  return username.hashCode();
 }

 @Override
 public String toString() {
  StringBuilder sb = new StringBuilder();
  sb.append(super.toString()).append(": ");
  sb.append("Username: ").append(this.username).append("; ");
  sb.append("Password: [PROTECTED]; ");
  sb.append("Enabled: ").append(this.enabled).append("; ");
  sb.append("AccountNonExpired: ").append(this.accountNonExpired).append(
    "; ");
  sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired)
    .append("; ");
  sb.append("AccountNonLocked: ").append(this.accountNonLocked).append(
    "; ");

  if (!authorities.isEmpty()) {
   sb.append("Granted Authorities: ");

   boolean first = true;
   for (GrantedAuthority auth : authorities) {
    if (!first) {
     sb.append(",");
    }
    first = false;

    sb.append(auth);
   }
  } else {
   sb.append("Not granted any authorities");
  }

  return sb.toString();
 }

}

 

 

package com.snda.swp.account.service;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Sets;
import com.snda.swp.account.po.Authority;
import com.snda.swp.account.po.Role;
import com.snda.swp.account.po.User;
import com.snda.swp.account.po.UserInfo;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 *
 * @author calvin
 */
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

 private AccountManager accountManager;

 /**
  * 获取用户Details信息的回调函数.
  */
 public UserDetails loadUserByUsername(String username)
   throws UsernameNotFoundException, DataAccessException {
  User user = accountManager.findUserByLoginName(username);
  if (user == null) {
   throw new UsernameNotFoundException("用户" + username + " 不存在");
  }

  Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);

  // -- mini-web示例中无以下属性, 暂时全部设为true. --//
  boolean enabled = true;
  boolean accountNonExpired = true;
  boolean credentialsNonExpired = true;
  boolean accountNonLocked = true;

  UserInfo userdetails = new UserInfo(user.getPassword(), user.getName(),
    user.getEmail(), user.getLoginName(), grantedAuths,
    accountNonExpired, accountNonLocked, credentialsNonExpired,
    enabled);

  return userdetails;
 }

 /**
  * 获得用户所有角色的权限集合.
  */
 private Set<GrantedAuthority> obtainGrantedAuthorities(User user) {
  Set<GrantedAuthority> authSet = Sets.newHashSet();
  for (Role role : user.getRoleList()) {
   for (Authority authority : role.getAuthorityList()) {
    authSet.add(new GrantedAuthorityImpl(authority
      .getPrefixedName()));
   }
  }
  return authSet;
 }

 @Autowired
 public void setAccountManager(AccountManager accountManager) {
  this.accountManager = accountManager;
 }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值