2017-05-17 8 views
0

저는 spring-security에서는 새로운 기능을하고 springboot에서는 spring-security-oauth2를 사용합니다.스프링 보안 CustomUserDetails가 작동하지 않습니다. SecurityContextHolder.getContext(). getAuthentication(). getPrincipal() 단지 사용자 이름을 반환합니다.

추가 속성이 필요하므로 UserDetails 및 UserDetailsService를 사용자 지정했습니다.

public class CustomUserDetails implements UserDetails { 

    private User user; 
    private Long id; 

    public CustomUserDetails(User user) { 
     this.user = user; 
     this.id = user.getId(); 
    } 

    @Override 
    public Collection<? extends GrantedAuthority> getAuthorities() { 
     return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"); 
    } 

    @Override 
    public String getPassword() { 
     return user.getPassword(); 
    } 

    @Override 
    public String getUsername() { 
     return user.getMobile(); 
    } 

    @Override 
    public boolean isAccountNonExpired() { 
     return true; 
    } 

    @Override 
    public boolean isAccountNonLocked() { 
     return true; 
    } 

    @Override 
    public boolean isCredentialsNonExpired() { 
     return true; 
    } 

    @Override 
    public boolean isEnabled() { 
     return true; 
    } 
} 

@Service("customUserDetailsService") 
public class CustomUserDetailsService implements UserDetailsService { 

    @Autowired 
    private UserMapper userMapper; 

    @Override 
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException { 

     // my model User 
     User user = userMapper.selectByPhone(phone); 

     if (user == null) { 
      throw new UsernameNotFoundException(""); 
     } 

     return new CustomUserDetails(user); 

    } 
} 

@Configuration 
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Autowired 
    @Qualifier("customUserDetailsService") 
    private UserDetailsService userDetailsService; 

    @Override 
    @Bean 
    public AuthenticationManager authenticationManagerBean() throws Exception { 
     return super.authenticationManagerBean(); 
    } 

    @Override 
    protected void configure(final HttpSecurity http) throws Exception { 
     http 
      .anonymous().disable() 
      .authorizeRequests() 
      .antMatchers("/oauth/token").permitAll() 
      .anyRequest().authenticated(); 
    } 

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

@Configuration 
@EnableAuthorizationServer 
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { 

    @Autowired 
    @Qualifier("authenticationManagerBean") 
    private AuthenticationManager authenticationManager; 

    @Autowired 
    private DataSource dataSource; 

    @Autowired 
    @Qualifier("customUserDetailsService") 
    private UserDetailsService userDetailsService; 

    @Override 
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { 
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); 
    } 

    @Override 
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception { 
     clients 
      .jdbc(dataSource); 
    } 

    public DefaultTokenServices tokenServices() { 
     final DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); 
     defaultTokenServices.setTokenStore(tokenStore()); 
     defaultTokenServices.setSupportRefreshToken(true); 
     defaultTokenServices.setAccessTokenValiditySeconds(100); 
     defaultTokenServices.setRefreshTokenValiditySeconds(10000); 
     return defaultTokenServices; 
    } 

    @Override 
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 
     endpoints 
      .tokenStore(tokenStore()) 
      .tokenServices(tokenServices()) 
      .userDetailsService(userDetailsService) 
      .authenticationManager(authenticationManager); 
    } 

    @Bean 
    public TokenStore tokenStore() { 
     return new JdbcTokenStore(dataSource); 
    } 
} 

나는 SecurityContextHolder.getContext().getAuthentication().getPrincipal() 반환 CustomUserDetails하지 String를 호출합니다. 나는 인터넷에서 찾은 모든 것을 시도했지만 아무것도 작동하지 않는다.

답변

-1

당신은 같은 세션 범위와 콩 (봄 구성 요소)를 만들 수 있습니다

import com.tk.graph.app.model.MyUser; 
import com.tk.graph.app.repository.MyUserRepository; 

@Component 
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS) 
public class LoggedUserBean { 

    @Autowired 
    private MyUserRepository MyUserDao; 

    private MyUser MyUser; 

    public MyUser getMyUser() { 
     if(MyUser==null){ 
      System.out.println("Etait null "); 
      Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
      MyUser = MyUserDao.findByLogin(auth.getName()).get(0); 
     } 
     return MyUser; 
    } 

    public void setMyUser(MyUser MyUser) { 
     this.MyUser = MyUser; 
    } 
} 

을하고 @Autowired 주석을 사용하는 스프링 composent에서 호출 할 수 있습니다.

+0

나는 이미 CustomUserDetailsService에서 사용자를 얻었으므로 데이터베이스를 통해 두 번 가져오고 싶지 않습니다. 어쨌든 감사합니다. –