【问题标题】:Spring WebClient and client_credentials grantSpring WebClient 和 client_credentials 授权
【发布时间】:2019-03-07 22:54:51
【问题描述】:

我的问题特定于 spring-security 5.1.0 并使用 Spring WebClient。我在使用 Spring Boot 2.1.0 的服务器环境中工作。这个question 可能已经被问过了,但当时无法回答。

阅读 spring-security 5.1.0 release notes,似乎他们已经添加了对 client_credentials 身份验证流程的支持,特别是将其添加到 WebClient Bean 中,因此最终用户不必担心身份验证令牌。我正试图做到这一点,但 API/文档让我完全迷失了。我目前的工作如下...

private ClientRegistration clientRegistration() {
    return ClientRegistration.withRegistrationId("registration-id")
        .clientId("client-id")
        .clientSecret("secret")
        .tokenUri("token-url")
        .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
        .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
        .scope("scopes")
        .build();
}

@Bean
public WebClient webClient() {
    ClientRegistrationRepository clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.clientRegistration());
    OAuth2AuthorizedClientService oAuth2AuthorizedClientService = new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
# These are unused ^ but pieces of documentation seem to indicate they are required

    return WebClient.builder()
        .filter(new ServerOAuth2AuthorizedClientExchangeFilterFunction()) # this requires 2 arguments that I do not have
        .build();
}

我的最终目标是能够在任何地方自动装配 WebClient bean,并且只需发出自动添加了 bearer 身份验证的请求。

【问题讨论】:

    标签: java spring spring-security spring-security-oauth2


    【解决方案1】:

    由于 Spring Security 5.1 为 OAuth2 身份验证机制添加了更简单的实现,我建议你看看这篇更新的帖子:StackOverflow - Spring Security 5.1 - Get token for client credentials flow with WebClient

    从现在开始,您无需管理任何ClientRegistration。一切都可以使用属性进行设置。

    然后,对于 WebClient 实例化,ClientRegistrationRepository需要从 Spring 注入,并且您需要使用 UnAuthenticatedServerOAuth2AuthorizedClientRepository 的新实例,因为您没有将任何用户附加到您的应用程序进程。这样,您将拥有ServerOAuth2AuthorizedClientExchangeFilterFunction 所需的两个参数。

    我尝试将客户端应用程序从资源服务器请求数据的场景放在使用 WebClient 在 GitHUb 存储库中的 OAuth2 安全端点上:GitHub - Spring Security OAuth2 Machine-To-Machine process。使用 Spring Security 5.1,身份验证机制现在变得非常容易。

    如果您有任何问题,请询问。希望对您有所帮助!

    【讨论】:

    • 我尝试在 github 上做一些类似于你的应用程序的事情,但是使用一个 Spring Boot Web 应用程序需要使用 client_credentails 进行远程 OAuth2 WebClient 调用,但从未让它工作。总是从 DefaultServerOAuth2AuthorizationRequestResolver 得到“无效的授权授予类型(client_credentials)”:(
    • 你有任何 GitHub 代码库,我可以看看吗?
    • @FlorentGornes :我的 Web 客户端有问题,它会在调用资源服务器之前为每个请求获取一个访问令牌。你已经测试了吗?
    猜你喜欢
    • 2018-05-15
    • 2019-09-17
    • 1970-01-01
    • 2014-05-22
    • 2020-04-25
    • 1970-01-01
    • 2016-05-19
    • 2022-08-22
    • 2023-04-05
    相关资源
    最近更新 更多