From 8f579a06fc551872899b0ae821b70ab4ddc9d196 Mon Sep 17 00:00:00 2001 From: Steve Riesenberg Date: Wed, 3 Nov 2021 15:38:59 -0500 Subject: [PATCH] Document authentication helper method in WebClient integration Closes gh-10120 --- .../pages/servlet/oauth2/oauth2-client.adoc | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc b/docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc index 427140c1e72..6d1cfc423db 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc @@ -2212,6 +2212,60 @@ fun index(): String { ==== <1> `clientRegistrationId()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. +The following code shows how to set an `Authentication` as a request attribute: + +==== +.Java +[source,java,role="primary"] +---- +@GetMapping("/") +public String index() { + String resourceUri = ... + + Authentication anonymousAuthentication = new AnonymousAuthenticationToken( + "anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); + String body = webClient + .get() + .uri(resourceUri) + .attributes(authentication(anonymousAuthentication)) <1> + .retrieve() + .bodyToMono(String.class) + .block(); + + ... + + return "index"; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@GetMapping("/") +fun index(): String { + val resourceUri: String = ... + + val anonymousAuthentication: Authentication = AnonymousAuthenticationToken( + "anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")) + val body: String = webClient + .get() + .uri(resourceUri) + .attributes(authentication(anonymousAuthentication)) <1> + .retrieve() + .bodyToMono() + .block() + + ... + + return "index" +} +---- +==== +<1> `authentication()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. + +[WARNING] +It is recommended to be cautious with this feature since all HTTP requests will receive an access token bound to the provided principal. + === Defaulting the Authorized Client