2013-05-04 164 views
0

我已经能够验证用户,并且可以获取他们登录的用户名以在他们的页面上显示。但不是用户名,我想使用用户名。Spring身份验证 - 获取登录名

此汇编:

@Service("assembler") 
public class Assembler { 

    @Transactional(readOnly = true) 
    public UserDetails buildUserFromUser(UserEntity userEntity) { 

     String username = userEntity.getUsername(); 
     String password = userEntity.getPassword(); 
     //String name = userEntity.getName(); 
     boolean enabled = userEntity.getActive(); 
     boolean accountNonExpired = enabled; 
     boolean credentialsNonExpired = enabled; 
     boolean accountNonLocked = enabled; 

     Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 
     for(Role role : userEntity.getRoles()) { 
      authorities.add(new SimpleGrantedAuthority(role.getName())); 
     } 

     User user = new 
     User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); 

     return user; 
    } 
} 

,我使用限制的集合构造,所以我不能获得通过它名字中的的UserDetails。有另一种方法可以做到这一点吗?

回答

2

您可以扩展User类,并让用户拥有所需的附加信息并从buildUserFromUser方法中返回该信息。事情是这样的:

public class CustomUser extends User { 
    private String name; 

    public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, String name) { 
     super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); 
     this.name = name; 
    } 

    public String getName() { 
     return name; 
    } 
} 

实例化这个用户在你的buildUserFromUser方法的名称经过距userEntity对象:

@Service("assembler") 
public class Assembler { 

@Transactional(readOnly = true) 
public UserDetails buildUserFromUser(UserEntity userEntity) { 

    String username = userEntity.getUsername(); 
    String password = userEntity.getPassword(); 
    String name = userEntity.getName(); 
    boolean enabled = userEntity.getActive(); 
    boolean accountNonExpired = enabled; 
    boolean credentialsNonExpired = enabled; 
    boolean accountNonLocked = enabled; 

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 
    for(Role role : userEntity.getRoles()) { 
     authorities.add(new SimpleGrantedAuthority(role.getName())); 
    } 

    return new CustomUser(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities, name); 
} 

然后你就可以得到这样的春季安全上下文自定义用户:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
String name = ((CustomUser)authentication.getPrincipal()).getName(); 
+0

是的,它工作绝对好。非常感谢。 – user2259555 2013-05-04 06:23:52