security-oauth2定制oauth2令牌请求的授权头?

jtoj6r0c  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(526)

我正在尝试通过网络客户端电话升级到SpringSecurity 5.5.1。我发现oauth2 clientid和secret现在是url编码的 AbstractWebClientReactiveOAuth2AccessTokenResponseClient ,但我的令牌提供程序不支持此操作(例如,如果机密包含 + 字符仅当它作为 + 不如 %2B ). 我知道这被看作是spring安全方面的一个bug修复),但我不能让令牌提供者轻易地改变其行为。
所以我试着找到一种方法来解决这个问题。
[文件](https://docs.spring.io/spring-security/site/docs/current/reference/html5/#customizing-当您使用webclient配置(这是我的情况)时,关于如何自定义访问令牌请求的访问令牌请求似乎不适用。
为了删除clientid/secret编码,我必须从中扩展和复制大部分现有代码 AbstractWebClientReactiveOAuth2AccessTokenResponseClient 自定义 WebClientReactiveClientCredentialsTokenResponseClient 因为它的大部分都具有私有/默认可见性。我在spring安全项目中的一个增强问题中对此进行了跟踪。
是否有更简单的方法自定义令牌请求的授权头,以跳过url编码?

wdebmtf2

wdebmtf21#

关于定制的一些API肯定有改进的余地,而且可以肯定的是,来自社区的这些类型的问题/请求/问题将继续有助于突出这些领域。
关于 AbstractWebClientReactiveOAuth2AccessTokenResponseClient 特别是,目前无法重写内部方法来填充数据库中的基本身份验证凭据 Authorization 标题。但是,您可以自定义 WebClient 用于进行api调用的。如果它在您的用例中是可接受的(暂时,在处理行为更改和/或添加自定义选项时),您应该能够在 WebClient .
下面是一个将创建 WebClient 能够使用 OAuth2AuthorizedClient :

@Configuration
public class WebClientConfiguration {

    @Bean
    public WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
        // @formatter:off
        ServerOAuth2AuthorizedClientExchangeFilterFunction exchangeFilterFunction =
                new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        exchangeFilterFunction.setDefaultOAuth2AuthorizedClient(true);

        return WebClient.builder()
                .filter(exchangeFilterFunction)
                .build();
        // @formatter:on
    }

    @Bean
    public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
            ReactiveClientRegistrationRepository clientRegistrationRepository,
            ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
        // @formatter:off
        WebClientReactiveClientCredentialsTokenResponseClient accessTokenResponseClient =
                new WebClientReactiveClientCredentialsTokenResponseClient();
        accessTokenResponseClient.setWebClient(createAccessTokenResponseWebClient());

        ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
                ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
                        .clientCredentials(consumer ->
                                consumer.accessTokenResponseClient(accessTokenResponseClient)
                                        .build())
                        .build();

        DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
                new DefaultReactiveOAuth2AuthorizedClientManager(
                        clientRegistrationRepository, authorizedClientRepository);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
        // @formatter:on

        return authorizedClientManager;
    }

    protected WebClient createAccessTokenResponseWebClient() {
        // @formatter:off
        return WebClient.builder()
                .filter((clientRequest, exchangeFunction) -> {
                    HttpHeaders headers = clientRequest.headers();
                    String authorizationHeader = headers.getFirst("Authorization");
                    Assert.notNull(authorizationHeader, "Authorization header cannot be null");
                    Assert.isTrue(authorizationHeader.startsWith("Basic "),
                            "Authorization header should start with Basic");
                    String encodedCredentials = authorizationHeader.substring("Basic ".length());
                    byte[] decodedBytes = Base64.getDecoder().decode(encodedCredentials);
                    String credentialsString = new String(decodedBytes, StandardCharsets.UTF_8);
                    Assert.isTrue(credentialsString.contains(":"), "Decoded credentials should contain a \":\"");
                    String[] credentials = credentialsString.split(":");
                    String clientId = URLDecoder.decode(credentials[0], StandardCharsets.UTF_8);
                    String clientSecret = URLDecoder.decode(credentials[1], StandardCharsets.UTF_8);

                    ClientRequest newClientRequest = ClientRequest.from(clientRequest)
                            .headers(httpHeaders -> httpHeaders.setBasicAuth(clientId, clientSecret))
                            .build();
                    return exchangeFunction.exchange(newClientRequest);
                })
                .build();
        // @formatter:on
    }

}

此测试演示了为内部访问令牌响应解码凭据 WebClient :

@ExtendWith(MockitoExtension.class)
public class WebClientConfigurationTests {

    private WebClientConfiguration webClientConfiguration;

    @Mock
    private ExchangeFunction exchangeFunction;

    @Captor
    private ArgumentCaptor<ClientRequest> clientRequestCaptor;

    @BeforeEach
    public void setUp() {
        webClientConfiguration = new WebClientConfiguration();
    }

    @Test
    public void exchangeWhenBasicAuthThenDecoded() {
        WebClient webClient = webClientConfiguration.createAccessTokenResponseWebClient()
                .mutate()
                .exchangeFunction(exchangeFunction)
                .build();
        when(exchangeFunction.exchange(any(ClientRequest.class)))
                .thenReturn(Mono.just(ClientResponse.create(HttpStatus.OK).build()));

        webClient.post()
                .uri("/oauth/token")
                .headers(httpHeaders -> httpHeaders.setBasicAuth("aladdin", URLEncoder.encode("open sesame", StandardCharsets.UTF_8)))
                .retrieve()
                .bodyToMono(Void.class)
                .block();

        verify(exchangeFunction).exchange(clientRequestCaptor.capture());

        ClientRequest clientRequest = clientRequestCaptor.getValue();
        String authorizationHeader = clientRequest.headers().getFirst("Authorization");
        assertThat(authorizationHeader).isNotNull();
        String encodedCredentials = authorizationHeader.substring("Basic ".length());
        byte[] decodedBytes = Base64.getDecoder().decode(encodedCredentials);
        String credentialsString = new String(decodedBytes, StandardCharsets.UTF_8);
        String[] credentials = credentialsString.split(":");

        assertThat(credentials[0]).isEqualTo("aladdin");
        assertThat(credentials[1]).isEqualTo("open sesame");
    }

}

相关问题