【发布时间】:2020-04-06 04:47:48
【问题描述】:
我想实现一个客户端,它应该简单地使用 OAuth2 令牌发送一些休息调用。使用 spring-security-oauth 很容易将 OAuth2RestTemplate 与客户端凭据流一起使用。今天我看到大多数这些类在 2.4.0 中已弃用,建议使用 Spring Security 5。我四处搜索并查看了迁移指南 [1],但我不明白我要做什么执行一些简单的休息调用,使用 Spring Security 5 获取令牌。我想我什至不确定需要什么样的库。所以我基本上正在寻找的是一种以编程方式(而不是通过属性)向某种休息模板提供客户端 ID、客户端秘密和令牌端点并将请求发送到特定 URL 的方法。
--编辑--
我找到了一种不使用属性而是使用ClientRegestration 对象来使用Web 客户端的方法。我不确定这是否是推荐的方式:
@Test
public void test() {
WebClient webClient = getWebClient();
ResponseSpec retrieve = webClient.get().uri("https://somepath")
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(REG_ID)).retrieve();
Flux<String> result = retrieve.bodyToFlux(String.class); // flux makes no sense here, use Mono instead
Mono<List<String>> response = result.collectList();
List<String> block = response.block();
System.out.print(block);
System.out.print("debug");
}
public WebClient getWebClient() {
Builder clientRegestrationBuilder = ClientRegistration.withRegistrationId(REG_ID);
clientRegestrationBuilder.clientId(CLIENT_ID);
clientRegestrationBuilder.clientSecret(CLIENT_SECRET);
clientRegestrationBuilder.tokenUri(TOKEN_ENDPOINT);
clientRegestrationBuilder.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS);
ClientRegistration clientRegistration = clientRegestrationBuilder.build();
ReactiveClientRegistrationRepository repo = new InMemoryReactiveClientRegistrationRepository(clientRegistration);
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(repo,
new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
return WebClient.builder().filter(oauth).build();
}
问候 蒙蒂
[1]https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Migration-Guide
【问题讨论】:
-
如果您正在寻找与 Spring
WebClient和 Spring Security 的 OAuth2 集成,请查看以下示例:rieckpil.de/… 或 rieckpil.de/… 用于基于 servlet 的应用程序 -
感谢您提供链接。我仍然有点困惑,但找到了一种方法来完成我对其余模板所做的事情。更新了我的帖子