首页 文章

spring security oauth2 ClassCastException配置DefaultTokenServices

提问于
浏览
7

我正在尝试使用spring boot和spring security oauth运行一个示例应用程序,其中包含已配置的JdbcTokenStore和一个具有无限生存期访问权限的DefaultTokenServices .

使用gradle bootRun运行此应用程序时,应用程序将无法启动并抛出“由以下引起:java.lang.ClassCastException:com.sun.proxy . $ Proxy51无法转换为org.springframework.security.oauth2.provider.token . DefaultTokenServices”

为什么在DefaultTokenServices bean周围有代理?

奇怪的是 - 使用InMemoryTokenStore运行应用程序......一切正常(参见内存分支) .

源代码https://github.com/grafjo/oauth_demo/blob/master/src/main/java/demo/AuthorizationServerConfiguration.java

完整追踪:http://pastebin.com/SUcwz4S5

5 回答

  • 0

    快速浏览DefaultTokenService,可以看到它是用@Transactional注释的 . Spring将把它包装在代理中以服务事务 - 因此你需要通过它的接口与类进行交互 .

    对于您的tokenService bean:

    @Bean
    public DefaultTokenServices tokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setAccessTokenValiditySeconds(-1);
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }
    

    尝试将其更改为:

    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setAccessTokenValiditySeconds(-1);
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }
    
  • 3

    我的应用程序中也有类似的异常,当将spring oauth版本从2.0.7.RELEASE更改为2.0.3.RELEASE时它起作用了 . 也许这是最新版本中的一个错误?

    EDIT: 从错误看似问题与spring创建的代理有关 . 当我将代理类型更改为CGLIB而不是默认动态代理时,它也适用于版本2.0.7 . 可以通过proxyTargetClass属性 @EnableTransactionManagement(proxyTargetClass = true) 设置此设置

    然而,这个解决方案对我没有吸引力,因为我更喜欢默认代理方法而不是CGLIB . 这里还有一篇解释代理方法的文章http://thecafetechno.com/tutorials/spring/spring-proxying-mechanisms/

  • 0

    这适用于版本2.0.7.RELEASE

    @Primary
     @Bean
     protected AuthorizationServerTokenServices tokenServices() throws Exception{
    

    将DefaultTokenServices更改为AuthorizationServerTokenServices后,Spring将抛出错误:

    没有定义[org.springframework.security.oauth2.provider.token.ResourceServerTokenServices]类型的限定bean:预期的单个匹配bean但找到3:defaultAuthorizationServerTokenServices,consumerTokenServices,tokenServices“}}

  • 7

    我在以下组合中使用2.0.9.RELEASE时遇到了同样的问题:

    pom.xml中:

    ...    
    <spring.version>4.1.4.RELEASE</spring.version>       
    <spring-security.version>3.2.5.RELEASE</spring-security.version>
    <spring-security-oauth2.version>2.0.9.RELEASE</spring-security-oauth2.version>
    ...
    

    并有相同的例外 .

    降级为

    ...
    <spring-security-oauth2.version>2.0.3.RELEASE</spring-security-oauth2.version>
    ...
    

    为我解决了问题 .

  • 1

    <aop:config proxy-target-class="true"/>
    

    在你的 spring 配置 .

相关问题