Spring Security 5.1 - Get Token for Client Credentials Flow with WebClient

前端 未结 1 2017
旧巷少年郎
旧巷少年郎 2021-01-03 08:53

I am attempting to get a bearer token via a webclient with the following setup for an integration test of a secured resource server in a servlet application.

1条回答
  •  醉梦人生
    2021-01-03 09:08

    The problem here is that you are not instancing your WebClient the right way.

    As you are on the client side, you do not have access to an OAuth2AuthorizedClientRepository. This bean is supposed to be linked to a resource sever on which you log into using the .oauth2Login() method declaration on the HttpSecurityconfiguration. These details are explained here : Spring Security 5 Oauth2 Login.

    Again, you are on the client side so what you need is an exchange filter function which will trigger a request to an authorization server to get a JWT token. You can use the ServerOAuth2AuthorizedClientExchangeFilterFunction instead.

    You better use a WebClientCustomizer to add the exchange filter function in the WebClient filter. Why ? Simply because injecting in your Spring application a WebClient.Builder will allow you accessing native metrics linked to web exchanges.

    Hence, you will build your WebClient using a new instance of an UnAuthenticatedServerOAuth2AuthorizedClientRepository bean like this :

    // Use injection to get an in-memory reposiroty or client registrations
    @Bean
    WebClient webClient(ClientRegistrationRepository clientRegistrations) {
    
        // Provides support for an unauthenticated user such as an application
        ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(
                clientRegistrations, new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
    
        // Build up a new WebClientCustomizer implementation to inject the oauth filter
        // function into the WebClient.Builder instance
        return new WebClientSecurityCustomizer(oauth);
    }
    

    As you are on the client side, you are not associating a user to your process, that's why you can not use any authorized client repository bean instanciation. Check on Spring Security documentation : Spring Security documentation : Class UnAuthenticatedServerOAuth2AuthorizedClientRepository.

    I tried to sum up a demo case in the following GitHub project : GitHub - Spring Security OAuth2 Machine-To-Machine scenario.

    I hope this gives you more insights on WebClient configuration. Please ask if you have any question.

    0 讨论(0)
提交回复
热议问题