2013-05-04 162 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