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

Spring OAuth2 Custom Authentication Manager ClassCastException

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

处理错误:

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

如果我使用默认身份验证管理器(spring 引导附带的那个)一切正常。

这里是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

在调试时,它会在某些混淆的 class.

中返回新的 UsernamePasswordAuthenticationToken 时中断

居然找到答案了。 问题出在进行此无效转换的 CustomTokenEnhancer 中。