java - Spring OAuth2 自定义认证管理器 ClassCastException

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

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

处理错误:

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

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

这里是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 时中断。

最佳答案

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

关于java - Spring OAuth2 自定义认证管理器 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50354766/

相关文章:

java - 使用 VSCode 发送电子邮件(spring-boot-starter-email)

spring - Grails中的垂直响应API

reactjs - spring boot jsp页面中如何导入react组件

spring - spring中如何并发读取并处理多个文件?

java - Axon:如何为单个事件配置 amqp 发布?

java - Spring Boot Rest 项目的推荐项目结构是什么?

java - Google Talk 是否支持 XMPP 多用户聊天?

java - 使用 Maven 模块化项目

java - 在数字迷宫中找到最短路径,Java

java - 从元注释重写 ContextHierarchy 和 ContextConfiguration