我正在尝试使用spring cloud feign创建一个简单的REST客户端来使用通过OAuth2安全令牌保护的服务。我使用OAuth2FeignRequestInterceptor添加持票令牌,请检查我的下面的代码。我正面临401.当我尝试调试我的代码时,我在Request对象中找不到持票人令牌。
@Configuration
@EnableConfigurationProperties(value=OAuth2ClientCredentialsProperties.class)
@EnableOAuth2Client
@Profile(OAuth2Profiles.CLIENT_CREDENTIALS)
public class ClientCredentialsConfiguration {
@Autowired
private OAuth2ClientCredentialsProperties oAuth2ClientCredentialsProperties;
@Bean
@Qualifier("ClientCredentialsOAuth2FeignRequestInterceptor")
public OAuth2FeignRequestInterceptor oauth2schemeRequestInterceptor() {
return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), oauth2schemeResourceDetails());
}
@Bean
public ClientCredentialsResourceDetails oauth2schemeResourceDetails() {
ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
details.setClientId(oAuth2ClientCredentialsProperties.getClientId());
details.setClientSecret(oAuth2ClientCredentialsProperties.getClientSecret());
details.setAccessTokenUri(oAuth2ClientCredentialsProperties.getAccessTokenUri());
details.setScope(oAuth2ClientCredentialsProperties.getScopes());
return details;
}
}
这是我的客户端界面
@FeignClient(name = "test", url = "http://localhost:8080", configuration = ClientCredentialsConfiguration.class)
interface GitHubClient {
@RequestMapping(value = "/api/v1/products",
produces = "application/json",
consumes = "application/json;charset=UTF-8",
method = RequestMethod.POST)
ResponseEntity<Object> testUsingPOST(@RequestBody TestDTO testDTO);
我的属性低于
server.port=10080
security.user.name=admin
security.user.password=admin
security.basic.enabled=false
org.springframework.boot.autoconfigure.EnableAutoConfiguration=sgcib.clips.bcsapi.configuration.ClientCredentialsConfiguration
feign.oauth2.enabled=true
feign.hystrix.enabled=false
我的主要课程
@SpringBootApplication
@EnableWebMvc
@Controller
@EnableFeignClients
@EnableAutoConfiguration
public class App extends SpringBootServletInitializer {
@Autowired
private GitHubClient gitHub;
@RequestMapping("/")
public String home() {
return "index";
}
@RequestMapping("/{owner}")
@ResponseBody
public ResponseEntity<Object> contributors(@PathVariable String owner) {
return gitHub.productsUsingPOST(new TestDTO());
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
答案 0 :(得分:2)
我也在使用假请求拦截器。对我来说,它将@Bean方法返回类型更改为通用RequestInterceptor。像这样:
@Bean
public RequestInterceptor oauth2FeignRequestInterceptor() {
return new OAuth2FeignRequestInterceptor(...);
}
此教程还介绍了如何使用feign设置OAuth: spring-cloud-feign-oauth2
答案 1 :(得分:0)
我发现了这个问题,这是由于ClientCredentialsConfiguration类中的注释@Profile(OAuth2Profiles.CLIENT_CREDENTIALS)。我错过了启用配置文件,所以我的拦截器Bean根本没有加载。