2013-05-04 6 views
0

사용자를 인증 할 수 있었으며 로그인 된 사용자 이름을 페이지에 표시 할 수 있습니다. 그러나 사용자 이름 대신 사용자 이름을 사용하고 싶습니다. 이것에 대한스프링 인증 - 로그인 한 이름 얻기

어셈블러 :

@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

클래스를 확장하여 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; 
    } 
} 

인스턴스화 userEntity 객체에서 이름을 전달하여 buildUserFromUser 방법이 사용자 :

@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

관련 문제