Feign Oauth2客户端令牌异常

时间:2018-09-13 13:41:41

标签: java spring spring-security-oauth2 spring-cloud-feign

我正试图让假冒客户处理我的Oauth2 SSO

我已经如下定义了一个bean拦截器

@Bean
        @LoadBalanced
        RequestInterceptor oauthFeignClient(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) {
            return new OAuth2FeignRequestInterceptor(oauth2ClientContext, details);
        }

但是我遇到了这个异常:

  

feign.FeignException:状态401读取AppClientFeign#getApps();内容:   {“错误”:“ invalid_token”,“错误描述”:“ 9d8eb02c-7005-487e-b28f-19417e5fea51”}

我不知道为什么要得到这个

这是我的身份验证服务器

 @Configuration
        static class MvcConfig extends WebMvcConfigurerAdapter {

            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("login").setViewName("login");
            registry.addViewController("/oauth/confirm_access").setViewName("authorize");
            registry.addViewController("/").setViewName("index");
            }
        }

        @Configuration
        static class LoginConfig extends WebSecurityConfigurerAdapter {


            @Bean
            public PasswordEncoder passwordEncoder() {
                return new BCryptPasswordEncoder();
            }
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .formLogin().loginPage("/login").permitAll()
                        .and().logout().clearAuthentication(true).invalidateHttpSession(true).logoutUrl("/exit").logoutSuccessUrl("http://localhost:9999/client").permitAll()
                    .and()
                        .authorizeRequests()
                        .antMatchers("/","/exit","/graphics/**", "/login", "/oauth/authorize", "/oauth/confirm_access").permitAll()
                    .and()
                        .authorizeRequests()
                        .anyRequest().authenticated()
                        .and().httpBasic().disable().csrf().disable();
            }

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


        }

和我的Yaml配置

security:
    oauth2:
      client:
        client-id: xxx
        client-secret: xxx
        scope: read, write
        auto-approve-scopes: .*
      authorization:
        check-token-access: permitAll()

这是我的客户

@SpringBootApplication
@EnableOAuth2Sso
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
@EnableWebSecurity
public class ClientApplication extends WebSecurityConfigurerAdapter{


    public static void main(String[] args) {
        SpringApplication.run(ClientApplication.class, args);
    }


        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .logout()
                    .logoutSuccessUrl("http://localhost:9999/uaa/exit");
            http.authorizeRequests().antMatchers("graphics/**").permitAll().
                    and().authorizeRequests().anyRequest().authenticated();
        }


        @Bean
        @LoadBalanced
        RequestInterceptor oauthFeignClient(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) {
            return new OAuth2FeignRequestInterceptor(oauth2ClientContext, details);
        }

    @Bean
    @LoadBalanced
    OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) {
        return new OAuth2RestTemplate(details, oauth2ClientContext);
    }

    @Profile("!cloud")
    @Bean
    RequestDumperFilter requestDumperFilter() {
        return new RequestDumperFilter();
    }

}

假客户端界面

@FeignClient("USERS-MANAGER")
public interface UserClientFeign {
      @GetMapping("/users/info")
      public User getUserDetails(@RequestParam("username") String username);
}

我的客户端的yml配置

security:
  basic:
    enabled: false
  oauth2:
    client:
      client-id: xxx
      client-secret: xxx
      access-token-uri: ${auth-server}/oauth/token
      user-authorization-uri: ${auth-server}/oauth/authorize
      scope: read, write
    resource:
      token-info-uri: ${auth-server}/oauth/check_token

最后我的资源

@SpringBootApplication
@EnableResourceServer
@EnableEurekaClient
@RestController
public class ResourceApplication extends ResourceServerConfigurerAdapter {



    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
                .antMatchers(HttpMethod.GET, "/users/**").access("#oauth2.hasScope('read')")
                .antMatchers(HttpMethod.POST, "/users/**").access("#oauth2.hasScope('write')");
    }

    public static void main(String[] args) {
        SpringApplication.run(ResourceApplication.class, args);
    }

    @Profile("!cloud")
    @Bean
    RequestDumperFilter requestDumperFilter() {
        return new RequestDumperFilter();
    }
}

yml配置

spring.application.name: USERS-MANAGER

server:
  port: 0

ribbon:
    eureka:
        enabled: true

eureka.client.service-url.defaultZone: http://localhost:8761/eureka/

security:
  oauth2:
    resource:
      token-info-uri:  http://localhost:9999/uaa/oauth/check_token
    client:
      client-id:  xxx
      client-secret:  xxx

浏览器中的异常

  

BST 2018年9月13日14:19:52   发生意外错误(类型=内部服务器错误,状态= 500)。   状态401读取AppClientFeign#getApps();内容:{“错误”:“无效令牌”,“错误描述”:“ 9d8eb02c-7005-487e-b28f-19417e5fea51”}

1 个答案:

答案 0 :(得分:1)

在没有任何详细描述的情况下找出令牌无效的原因非常棘手。可能是令牌过期太快(由于设置了令牌TTL),或者令牌的授予类型或者令牌的范围与资源服务器的要求不同。

您可能想在OAuth2AuthenticationProcessingFilter#doFilter()的多个位置添加断点,并查看从oauth2提供程序获取的值是什么,并将其与客户端使用的令牌值进行比较。尤其是在authenticationManager.authenticate(authentication);

附近看一下电话