具有OAuth2的Spring Security 5 Rest Client

时间:2019-12-12 18:17:11

标签: spring spring-security

我想实现一个客户端,该客户端应仅发送带有OAuth2令牌的一些其他调用。使用spring-security-oauth,将OAuth2RestTemplate与客户端凭证流一起使用非常容易。今天,我看到其中的大多数类都已在2.4.0中弃用,建议使用Spring Security5。我四处搜寻并查看了《迁移指南》 [1],但我不知道该怎么做。执行一些简单的Rest调用,使用Spring Security 5来获取令牌。我想我什至不知道需要哪种类型的库。因此,我基本上想寻找的是一种以编程方式(不是通过属性)为某种类型的rest模板提供client-id,client-secret和tokenendpoint的方法,并将请求发送到特定的url。

-编辑-

我找到了一种使用Web客户端而不使用属性而是使用ClientRegestration对象的方法。我不确定这是否是推荐的方法:

 @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

1 个答案:

答案 0 :(得分:0)

以下代码是单元测试,它显示了如何以编程方式完成func updateDataBase(_ vv:String,completion:@escaping(()->())) ref.setValue(<##>) { (error, ref) -> Void in completion() } } 。在“真实”春季场景中,我猜想ClientRegistration应该作为bean提供,并最终作为列表注入ClientRegistration ...

ReactiveClientRegistrationRepository