2014-08-19 3 views
13

사용자 주체 오브젝트에 추가 데이터를 저장하려고합니다. 내가 무슨 짓을스프링 보안 사용자 정의 UserDetailsService 및 사용자 정의 사용자 클래스

했다 :

는 (이메일 주소와 같은 등) 내 추가 데이터가 저장되어 기존 사용자 클래스에 "된 UserDetails"인터페이스를 구현합니다.

@Service 
public class UserDetailsServiceImpl implements UserDetailsService { 

    @Autowired 
    UserDAO userDAO; 

    @Override 
    public UserDetails loadUserByUsername(String username) 
      throws UsernameNotFoundException { 
     User user = userDAO.findOneByUsername(username); 
     if (user == null) 
      throw new UsernameNotFoundException("username " + username 
        + " not found"); 

     System.out.println("---------------------> FOUND ------------->" 
       + user.getEmail()); 

     return user; 
    } 

} 

마지막 단계는 내 보안 구성에서 UserDetailsService도 추가했다 :

@Entity 
public class User implements UserDetails { 

그런 다음 나는 UserDetailsService의 구현을 만들었습니다.

@Configuration 
@EnableWebMvcSecurity 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

@Autowired 
UserDetailsService userDetailsService; 



@Override 
protected void configure(AuthenticationManagerBuilder auth) 
     throws Exception { 
    auth.userDetailsService(userDetailsService()); 
// ... 

} 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.userDetailsService(userDetailsService()); 
// ... 
} 

@Override 
protected UserDetailsService userDetailsService() { 
    return userDetailsService; 
} 

내 콘솔에서 "found"출력으로 인해 "loadUserByName"이 두 번 호출됩니다.

내가 내 컨트롤러에 주요 개체에 액세스하려고

->

내 추가 데이터를 얻을 해달라고
System.out.println(SecurityContextHolder.getContext() 
       .getAuthentication().getPrincipal()); 

. 내가 내 사용자 개체에 캐스팅하려고하면 예외를 캐스팅하지 못했습니다.

내가 누락 된 것이 있습니까?

미리 감사드립니다. UserDetailsService도에 추가보다

public class CustomUserDetails extends org.springframework.security.core.userdetails.User{ 

    private User user; 

    public CustomUserDetails(User user, Collection<? extends GrantedAuthority> authorities) { 
     super(user.getName(), user.getPassword(), authorities); 
     this.user = user; 
    } 

    public CustomUserDetails(User user, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) { 
     super(user.getName(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); 
     this.user = user; 
    } 

    public User getUser() { 
     return user; 
    } 
} 

: 증축 클래스 만들기

답변

11

확인. 내 문제는 코드에서 내가 게시물을하지 않았다.

이 세부 정보 서비스는 추가 세부 정보 만 얻는 것이지만 로그인 자체에 사용되는 것으로 생각했습니다.

"jdbcAuthentication"이 추가로 구성되었고 스프링이 항상 이것을 사용하는 것으로 보입니다.

이제는 detailsService 만 설정하면 모든 것이 올바르게 작동합니다.

편집 :

는 그래서는이 코드를 삭제했다 :

auth.jdbcAuthentication() .dataSource(dataSource) 
    * .passwordEncoder(passwordEncoder) .usersByUsernameQuery(
// .... 

을 그리고 지금은 위의 질문에 내 코드와 함께 작동합니다.

0

@Service("userDetailsService") 
public class UserDetailsServiceImpl implements UserDetailsService { 
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException, DataAccessException { 
    UserDetails userDetails = null; 
    User user = userService.getByLogin(login); 
    userDetails = new CustomUserDetails(user, 
       true, true, true, true, 
       getAuthorities(user.getRole())); 

    return userDetails; 
} 

을 잡아!

(CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal() 
+0

아무 것도 바뀌지 않았습니다. Btw. 마지막 코드 조각이 나를 준다 : "java.lang.ClassCastException : org.springframework.security.core.userdetails.User를 캐스팅 할 수 없다 .......... CustomUserDetails" – jvecsei

+0

앱을 디버그하여 어떤 클래스가'SecurityContextHolder.getContext(). getAuthentication(). getPrincipal()'을 리턴할까요? –

+0

클래스 org.springframework.security.core.userdetails.사용자 – jvecsei

관련 문제