How should I use the Spring WebClient to non-interactively access an OAuth protected resource on behalf of another user?Access to User ID in SpringTrying to protect resources with OAuth in Spring MVCSpring Security + OAuth, fallback if access token absentHow to bypass access confirmation step in Spring security OAuth2 if user has previously authorized access?Access protected resource from client_credential grant type with spring bootHow to add client_id to requests performed by Spring Boot OAuth Security for TwitchSpring Oauth2 “Full authentication is required to access this resource” with valid access tokenHow to execute some code whenever new access token is inserted in spring-security-oauth?How to mock Spring WebClient in Unit TestRole based authentication in spring security OAuth in resource server

What game is this character in the Pixels movie from?

13th chords on guitar

Making a wall made from glass bricks

Why can't you move another user's directory when you can move their file?

Why did the Apple //e make a hideous noise if you inserted the disk upside down?

/etc/hosts not working

Is it okay to submit a paper from a master's thesis without informing the advisor?

What European countries have secret voting within the Legislature?

Discworld quote about an "old couple" who having said everything to each other, can finally go about living their lives

What do you call a notepad used to keep a record?

The Lucas argument vs the theorem-provers--who wins and why?

How do I create a new column in a dataframe from an existing column using conditions?

When casting a spell with a long casting time, what happens if you don't spend your action on a turn to continue casting?

Does friction always oppose motion?

Do home values typically rise and fall consistently across different price ranges?

List Manipulation : a,b,c,d,e,f,g,h into a,b,c,d,e,f,g,h

How do I ensure my employees don't abuse my flexible work hours policy?

What happens if a caster is surprised while casting a spell with a long casting time?

Why wasn't EBCDIC designed with contiguous alphanumeric characters?

If you kill a Solar Angel can you use its Slaying Longbow?

What verb for taking advantage fits in "I don't want to ________ on the friendship"?

Why were the first airplanes "backwards"?

if a USA citizen marries a foreign citizen who has kid from previous marriage

Calculus, Water Poured into a Cone: Why is Derivative Non-linear?



How should I use the Spring WebClient to non-interactively access an OAuth protected resource on behalf of another user?


Access to User ID in SpringTrying to protect resources with OAuth in Spring MVCSpring Security + OAuth, fallback if access token absentHow to bypass access confirmation step in Spring security OAuth2 if user has previously authorized access?Access protected resource from client_credential grant type with spring bootHow to add client_id to requests performed by Spring Boot OAuth Security for TwitchSpring Oauth2 “Full authentication is required to access this resource” with valid access tokenHow to execute some code whenever new access token is inserted in spring-security-oauth?How to mock Spring WebClient in Unit TestRole based authentication in spring security OAuth in resource server






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3















I have a Spring (not Boot) application which has to access non-interactively (in a scheduled task) some 3rd-party resources on behalf of our users. These resources use OAuth 2.0 for authorization. We already have a workflow that gets us the required tokens and are accessing the resources using either Spring Social or our own implementation neither of which is optimal (Spring Social seems to be not maintained, we'd rather use a library than maintain our OAuth "framework").



I'm trying to use the WebClient from Spring Security 5.1, but I'm not sure I'm using it correctly.



The WebClient is created this way:



final ClientRegistration 3rdParty = 3rdParty();

final ReactiveClientRegistrationRepository clientRegistrationRepository =
new InMemoryReactiveClientRegistrationRepository(3rdParty);

final ReactiveOAuth2AuthorizedClientService authorizedClientService =
new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);

final ServerOAuth2AuthorizedClientRepository authorizedClientRepository =
new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);

final ServerOAuth2AuthorizedClientExchangeFilterFunction autorizedClientExchangeFilterFunction =
new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository);

return WebClient.builder()
.filter(autorizedClientExchangeFilterFunction)
.build();


and accessing the resource this way works:



final OAuth2AuthorizedClient oAuth2AuthorizedClient = ... // (OAuth2AuthorizedClient with OAuth2AccessToken)

final Mono<SomeResource> someResourceMono = webClient().get()
.uri(3rdpartyUrl)
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(oAuth2AuthorizedClient))
.retrieve()
.bodyToMono(SomeResource.class);


The problem is I don't see how the ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository are used in this approach. If I have to create a fully populated OAuth2AuthorizedClient to access the resource, why are these repositories needed?



I expected, that I have to pass the clientRegistrationId, some "principalName", implement our ReactiveOAuth2AuthorizedClientService loading OAuth2AuthorizedClient's by "principalName" and let the ServerOAuth2AuthorizedClientRepository do its work, but the only way I see to pass a principal to the WebClient is by using ServerOAuth2AuthorizedClientExchangeFilterFunction#oauth2AuthorizedClient which requires a complete OAuth2AuthorizedClient. Which is the part I'm doing it wrong?










share|improve this question




























    3















    I have a Spring (not Boot) application which has to access non-interactively (in a scheduled task) some 3rd-party resources on behalf of our users. These resources use OAuth 2.0 for authorization. We already have a workflow that gets us the required tokens and are accessing the resources using either Spring Social or our own implementation neither of which is optimal (Spring Social seems to be not maintained, we'd rather use a library than maintain our OAuth "framework").



    I'm trying to use the WebClient from Spring Security 5.1, but I'm not sure I'm using it correctly.



    The WebClient is created this way:



    final ClientRegistration 3rdParty = 3rdParty();

    final ReactiveClientRegistrationRepository clientRegistrationRepository =
    new InMemoryReactiveClientRegistrationRepository(3rdParty);

    final ReactiveOAuth2AuthorizedClientService authorizedClientService =
    new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);

    final ServerOAuth2AuthorizedClientRepository authorizedClientRepository =
    new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);

    final ServerOAuth2AuthorizedClientExchangeFilterFunction autorizedClientExchangeFilterFunction =
    new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository);

    return WebClient.builder()
    .filter(autorizedClientExchangeFilterFunction)
    .build();


    and accessing the resource this way works:



    final OAuth2AuthorizedClient oAuth2AuthorizedClient = ... // (OAuth2AuthorizedClient with OAuth2AccessToken)

    final Mono<SomeResource> someResourceMono = webClient().get()
    .uri(3rdpartyUrl)
    .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(oAuth2AuthorizedClient))
    .retrieve()
    .bodyToMono(SomeResource.class);


    The problem is I don't see how the ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository are used in this approach. If I have to create a fully populated OAuth2AuthorizedClient to access the resource, why are these repositories needed?



    I expected, that I have to pass the clientRegistrationId, some "principalName", implement our ReactiveOAuth2AuthorizedClientService loading OAuth2AuthorizedClient's by "principalName" and let the ServerOAuth2AuthorizedClientRepository do its work, but the only way I see to pass a principal to the WebClient is by using ServerOAuth2AuthorizedClientExchangeFilterFunction#oauth2AuthorizedClient which requires a complete OAuth2AuthorizedClient. Which is the part I'm doing it wrong?










    share|improve this question
























      3












      3








      3








      I have a Spring (not Boot) application which has to access non-interactively (in a scheduled task) some 3rd-party resources on behalf of our users. These resources use OAuth 2.0 for authorization. We already have a workflow that gets us the required tokens and are accessing the resources using either Spring Social or our own implementation neither of which is optimal (Spring Social seems to be not maintained, we'd rather use a library than maintain our OAuth "framework").



      I'm trying to use the WebClient from Spring Security 5.1, but I'm not sure I'm using it correctly.



      The WebClient is created this way:



      final ClientRegistration 3rdParty = 3rdParty();

      final ReactiveClientRegistrationRepository clientRegistrationRepository =
      new InMemoryReactiveClientRegistrationRepository(3rdParty);

      final ReactiveOAuth2AuthorizedClientService authorizedClientService =
      new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);

      final ServerOAuth2AuthorizedClientRepository authorizedClientRepository =
      new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);

      final ServerOAuth2AuthorizedClientExchangeFilterFunction autorizedClientExchangeFilterFunction =
      new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository);

      return WebClient.builder()
      .filter(autorizedClientExchangeFilterFunction)
      .build();


      and accessing the resource this way works:



      final OAuth2AuthorizedClient oAuth2AuthorizedClient = ... // (OAuth2AuthorizedClient with OAuth2AccessToken)

      final Mono<SomeResource> someResourceMono = webClient().get()
      .uri(3rdpartyUrl)
      .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(oAuth2AuthorizedClient))
      .retrieve()
      .bodyToMono(SomeResource.class);


      The problem is I don't see how the ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository are used in this approach. If I have to create a fully populated OAuth2AuthorizedClient to access the resource, why are these repositories needed?



      I expected, that I have to pass the clientRegistrationId, some "principalName", implement our ReactiveOAuth2AuthorizedClientService loading OAuth2AuthorizedClient's by "principalName" and let the ServerOAuth2AuthorizedClientRepository do its work, but the only way I see to pass a principal to the WebClient is by using ServerOAuth2AuthorizedClientExchangeFilterFunction#oauth2AuthorizedClient which requires a complete OAuth2AuthorizedClient. Which is the part I'm doing it wrong?










      share|improve this question














      I have a Spring (not Boot) application which has to access non-interactively (in a scheduled task) some 3rd-party resources on behalf of our users. These resources use OAuth 2.0 for authorization. We already have a workflow that gets us the required tokens and are accessing the resources using either Spring Social or our own implementation neither of which is optimal (Spring Social seems to be not maintained, we'd rather use a library than maintain our OAuth "framework").



      I'm trying to use the WebClient from Spring Security 5.1, but I'm not sure I'm using it correctly.



      The WebClient is created this way:



      final ClientRegistration 3rdParty = 3rdParty();

      final ReactiveClientRegistrationRepository clientRegistrationRepository =
      new InMemoryReactiveClientRegistrationRepository(3rdParty);

      final ReactiveOAuth2AuthorizedClientService authorizedClientService =
      new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);

      final ServerOAuth2AuthorizedClientRepository authorizedClientRepository =
      new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);

      final ServerOAuth2AuthorizedClientExchangeFilterFunction autorizedClientExchangeFilterFunction =
      new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository);

      return WebClient.builder()
      .filter(autorizedClientExchangeFilterFunction)
      .build();


      and accessing the resource this way works:



      final OAuth2AuthorizedClient oAuth2AuthorizedClient = ... // (OAuth2AuthorizedClient with OAuth2AccessToken)

      final Mono<SomeResource> someResourceMono = webClient().get()
      .uri(3rdpartyUrl)
      .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(oAuth2AuthorizedClient))
      .retrieve()
      .bodyToMono(SomeResource.class);


      The problem is I don't see how the ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository are used in this approach. If I have to create a fully populated OAuth2AuthorizedClient to access the resource, why are these repositories needed?



      I expected, that I have to pass the clientRegistrationId, some "principalName", implement our ReactiveOAuth2AuthorizedClientService loading OAuth2AuthorizedClient's by "principalName" and let the ServerOAuth2AuthorizedClientRepository do its work, but the only way I see to pass a principal to the WebClient is by using ServerOAuth2AuthorizedClientExchangeFilterFunction#oauth2AuthorizedClient which requires a complete OAuth2AuthorizedClient. Which is the part I'm doing it wrong?







      spring spring-security spring-security-oauth2






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 25 at 14:51









      piotrekpiotrek

      1632 silver badges12 bronze badges




      1632 silver badges12 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Instead of supplying the OAuth2AuthorizedClient via oauth2AuthorizedClient(), you can also provide the clientRegistrationId via clientRegistrationId() and ServerWebExchange via serverWebExchange(). The combination of the latter 2 options will resolve the Principal from the ServerWebExchange and use both ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository to resolve the OAuth2AuthorizedClient. I understand your use-case is a bit different given you are running outside of a request context - this is just a FYI.




          ...The problem is I don't see how the
          ReactiveClientRegistrationRepository and
          ServerOAuth2AuthorizedClientRepository are used in this approach




          You still need to provide ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository as the ServerOAuth2AuthorizedClientExchangeFilterFunction supports the refreshing (authorization_code client) and renewing (client_credentials client) of an expired access token.



          For your specific use case, take a look at UnAuthenticatedServerOAuth2AuthorizedClientRepository as this implementation supports WebClient running outside of a request context, e.g. background thread. Here is a sample for your reference.






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55340549%2fhow-should-i-use-the-spring-webclient-to-non-interactively-access-an-oauth-prote%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Instead of supplying the OAuth2AuthorizedClient via oauth2AuthorizedClient(), you can also provide the clientRegistrationId via clientRegistrationId() and ServerWebExchange via serverWebExchange(). The combination of the latter 2 options will resolve the Principal from the ServerWebExchange and use both ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository to resolve the OAuth2AuthorizedClient. I understand your use-case is a bit different given you are running outside of a request context - this is just a FYI.




            ...The problem is I don't see how the
            ReactiveClientRegistrationRepository and
            ServerOAuth2AuthorizedClientRepository are used in this approach




            You still need to provide ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository as the ServerOAuth2AuthorizedClientExchangeFilterFunction supports the refreshing (authorization_code client) and renewing (client_credentials client) of an expired access token.



            For your specific use case, take a look at UnAuthenticatedServerOAuth2AuthorizedClientRepository as this implementation supports WebClient running outside of a request context, e.g. background thread. Here is a sample for your reference.






            share|improve this answer



























              0














              Instead of supplying the OAuth2AuthorizedClient via oauth2AuthorizedClient(), you can also provide the clientRegistrationId via clientRegistrationId() and ServerWebExchange via serverWebExchange(). The combination of the latter 2 options will resolve the Principal from the ServerWebExchange and use both ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository to resolve the OAuth2AuthorizedClient. I understand your use-case is a bit different given you are running outside of a request context - this is just a FYI.




              ...The problem is I don't see how the
              ReactiveClientRegistrationRepository and
              ServerOAuth2AuthorizedClientRepository are used in this approach




              You still need to provide ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository as the ServerOAuth2AuthorizedClientExchangeFilterFunction supports the refreshing (authorization_code client) and renewing (client_credentials client) of an expired access token.



              For your specific use case, take a look at UnAuthenticatedServerOAuth2AuthorizedClientRepository as this implementation supports WebClient running outside of a request context, e.g. background thread. Here is a sample for your reference.






              share|improve this answer

























                0












                0








                0







                Instead of supplying the OAuth2AuthorizedClient via oauth2AuthorizedClient(), you can also provide the clientRegistrationId via clientRegistrationId() and ServerWebExchange via serverWebExchange(). The combination of the latter 2 options will resolve the Principal from the ServerWebExchange and use both ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository to resolve the OAuth2AuthorizedClient. I understand your use-case is a bit different given you are running outside of a request context - this is just a FYI.




                ...The problem is I don't see how the
                ReactiveClientRegistrationRepository and
                ServerOAuth2AuthorizedClientRepository are used in this approach




                You still need to provide ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository as the ServerOAuth2AuthorizedClientExchangeFilterFunction supports the refreshing (authorization_code client) and renewing (client_credentials client) of an expired access token.



                For your specific use case, take a look at UnAuthenticatedServerOAuth2AuthorizedClientRepository as this implementation supports WebClient running outside of a request context, e.g. background thread. Here is a sample for your reference.






                share|improve this answer













                Instead of supplying the OAuth2AuthorizedClient via oauth2AuthorizedClient(), you can also provide the clientRegistrationId via clientRegistrationId() and ServerWebExchange via serverWebExchange(). The combination of the latter 2 options will resolve the Principal from the ServerWebExchange and use both ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository to resolve the OAuth2AuthorizedClient. I understand your use-case is a bit different given you are running outside of a request context - this is just a FYI.




                ...The problem is I don't see how the
                ReactiveClientRegistrationRepository and
                ServerOAuth2AuthorizedClientRepository are used in this approach




                You still need to provide ReactiveClientRegistrationRepository and ServerOAuth2AuthorizedClientRepository as the ServerOAuth2AuthorizedClientExchangeFilterFunction supports the refreshing (authorization_code client) and renewing (client_credentials client) of an expired access token.



                For your specific use case, take a look at UnAuthenticatedServerOAuth2AuthorizedClientRepository as this implementation supports WebClient running outside of a request context, e.g. background thread. Here is a sample for your reference.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Apr 8 at 13:28









                Joe GrandjaJoe Grandja

                3061 silver badge7 bronze badges




                3061 silver badge7 bronze badges


















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55340549%2fhow-should-i-use-the-spring-webclient-to-non-interactively-access-an-oauth-prote%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현