Spring OAuth2自定义身份验证管理器ClassCastException

时间:2018-05-15 16:09:10

标签: java spring spring-boot spring-security spring-oauth2

我有一个大问题,不知道如何解决它... 我需要在我的spring启动应用程序中使用customAuthenticationManager进行第三方登录,但是当我声明自定义身份验证器时,我得到:

处理错误:

ClassCastException, java.lang.String cannot be cast to com.nexus.demooauth.models.User

如果我使用默认身份验证管理器(弹簧启动附带的那个),一切正常。

这是Websecurity.java

@Configuration 
public class WebSecurity extends WebSecurityConfigurerAdapter {

@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
    return new CustomAuthenticationManager();
}

AuthorizationServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


@Autowired
UserDetailsService customUserDetailsService;

@Autowired
DataSource dataSource;

@Autowired
private AuthenticationManager authenticationManager;        

@Bean
public PasswordEncoder passwordEncoder() {
    return new Plainencoder();
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {
    //configurer.userDetailsService(customUserDetailsService);
    configurer.authenticationManager(authenticationManager);
    configurer.tokenEnhancer(tokenEnhancer());
}

@Bean
public TokenEnhancer tokenEnhancer() {
    return new CustomTokenEnhancer();
}


@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory().withClient("gigy").secret("secret").accessTokenValiditySeconds(8400)
    .scopes("read", "write").authorizedGrantTypes("password", "refresh_token");
}

CustomAuthenticationManager.java

 @Service
    public class CustomAuthenticationManager implements AuthenticationManager{

private final Logger logger = LoggerFactory.getLogger(CustomAuthenticationManager.class);

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String username = authentication.getName();
    String pw       = authentication.getCredentials().toString();
    logger.info("was here" + username.toString() + " , " + pw.toString());

    return new UsernamePasswordAuthenticationToken(username, pw, authentication.getAuthorities());

}

它实际上是在记录器中打印

2018-05-15 17:58:34.453  INFO 7212 --- [nio-8089-exec-1] c.n.d.s.CustomAuthenticationManager      : was heretest , test

调试时,在某个混淆的类中返回新的UsernamePasswordAuthenticationToken时会中断。

1 个答案:

答案 0 :(得分:1)

实际上找到了anserw。 问题在于CustomTokenEnhancer正在进行无效转换。