我正在尝试将 spring-boot-starter-oauth2-client 与新的 Spring Framework 版本 6 HttpInterface 一起使用
@Configuration
public class RestClientConfig {
@Bean
public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager, RestClient.Builder restClientBuilder) {
OAuth2ClientHttpRequestInterceptor interceptor = new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
return restClientBuilder
.requestInterceptor(interceptor)
.build();
}
}
@RestController
public class LessonsController {
private final RestClient restClient;
public LessonsController(RestClient restClient) {
this.restClient = restClient;
}
@GetMapping("/lessons")
public String fetchLessons() {
return restClient.get()
.uri("https://someserver.om/someprotectedresource")
.attributes(clientRegistrationId("my-client"))
.retrieve()
.body(String.class);
}
}
spring:
application:
name: client-application
security:
oauth2:
client:
registration:
my-client:
provider: my-provider
client-id: ididid
client-secret: secretsecret
authorization-grant-type: client_credentials
scope: download
provider:
my-provider:
token-uri: https://provider.com/token
以上操作有效。我们从令牌提供商处获得了令牌确认,并从资源服务器处获得了资源并传递了令牌。这两个步骤都运行良好,很开心。
https://www.youtube.com/watch?v=aR580OCEp7w 我们现在想用新的 Spring Framework 版本 6 HttpInterface 做同样的事情
执行此操作时:
@Configuration
public class UserClientConfig {
private final RestClient restClient;
public UserClientConfig(OAuth2AuthorizedClientManager authorizedClientManager, RestClient.Builder restClientBuilder) {
OAuth2ClientHttpRequestInterceptor interceptor = new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
this.restClient = restClientBuilder
.requestInterceptor(interceptor)
.baseUrl("https://host.com")
.build();
}
@Bean
public UserClient userClient() {
RestClientAdapter adapter = RestClientAdapter.create(restClient);
return HttpServiceProxyFactory.builderFor(adapter)
.build()
.createClient(UserClient.class);
}
}
@HttpExchange(
url = "/v1",
accept = MediaType.APPLICATION_JSON_VALUE)
public interface UserClient {
@GetExchange("/protectedresource/full")
public User getUserById(@RequestParam Map<String, String> key value);
}
@GetMapping("/lessons")
public User fetchLessons() {
return userClient.getUserById(Map.of("foo", "bar"));
}
使用 HttpInterface 时,这不起作用。首先不会获取令牌。可能是因为缺少 @HttpExchange @GetExchange 的 .attributes(clientRegistrationId("id")),但不确定。
问题:如何将 Http 接口与 spring-boot-starter-oauth2-client token 结合?
您应该
setClientRegistrationIdResolver
在您的实例上OAuth2ClientHttpRequestInterceptor
:这是我在启动器
RestClient
WebClient
中所做的,它仅使用应用程序属性即可帮助自动配置具有各种请求授权机制(Basic
、Bearer
和 API 密钥)和 HTTP 代理的bean 。在你的情况下,这将提供:很可爱不是吗?
请注意,为了澄清起见,我将其重命名为:
my-client
从my-registration
@HttpExchange
到(UserClient
用作代理内部自动配置的名称)UserApi
userClient
RestClient
@Bean
@HttpExchange