我正在尝试创建一个简单的REST客户端,使用Spring cloud feign来使用受OAuth2安全令牌保护的服务。我正在使用OAuth2FlygnRequest estInterceptor添加不记名令牌,检查我下面的代码。我面对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);
}
我还将feign与请求拦截器一起使用。对我来说,它可以将@Bean方法返回类型更改为通用的Request estInterceptor。像这样:
@Bean
public RequestInterceptor oauth2FeignRequestInterceptor() {
return new OAuth2FeignRequestInterceptor(...);
}
本教程还很好地描述了如何使用feign设置OAuth:spring-cloud d-feign-oaut2
我发现了这个问题,这是由于ClientCretionalsConfiguration
类中的注释@Profile(OAuth2Profiles.CLIENT_CREDENTIALS)
。我错过了启用配置文件,所以我的拦截器Bean根本没有加载。