authorized-clients.adoc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. [[oauth2-client-additional-features]]
  2. = [[oauth2Client-additional-features]]Authorized Client Features
  3. This section covers additional features provided by Spring Security for OAuth2 client.
  4. [[oauth2-client-registered-authorized-client]]
  5. == [[oauth2Client-registered-authorized-client]]Resolving an Authorized Client
  6. The `@RegisteredOAuth2AuthorizedClient` annotation provides the ability to resolve a method parameter to an argument value of type `OAuth2AuthorizedClient`.
  7. This is a convenient alternative compared to accessing the `OAuth2AuthorizedClient` by using the `OAuth2AuthorizedClientManager` or `OAuth2AuthorizedClientService`.
  8. The following example shows how to use `@RegisteredOAuth2AuthorizedClient`:
  9. [tabs]
  10. ======
  11. Java::
  12. +
  13. [source,java,role="primary"]
  14. ----
  15. @Controller
  16. public class OAuth2ClientController {
  17. @GetMapping("/")
  18. public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) {
  19. OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
  20. ...
  21. return "index";
  22. }
  23. }
  24. ----
  25. Kotlin::
  26. +
  27. [source,kotlin,role="secondary"]
  28. ----
  29. @Controller
  30. class OAuth2ClientController {
  31. @GetMapping("/")
  32. fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String {
  33. val accessToken = authorizedClient.accessToken
  34. ...
  35. return "index"
  36. }
  37. }
  38. ----
  39. ======
  40. The `@RegisteredOAuth2AuthorizedClient` annotation is handled by `OAuth2AuthorizedClientArgumentResolver`, which directly uses an xref:servlet/oauth2/client/core.adoc#oauth2Client-authorized-manager-provider[`OAuth2AuthorizedClientManager`] and, therefore, inherits its capabilities.
  41. [[oauth2-client-rest-client]]
  42. == RestClient Integration
  43. Support for `RestClient` is provided by `OAuth2ClientHttpRequestInterceptor`.
  44. This interceptor provides the ability to make protected resources requests by placing a `Bearer` token in the `Authorization` header of an outbound request.
  45. The interceptor directly uses an `OAuth2AuthorizedClientManager` and therefore inherits the following capabilities:
  46. * Performs an OAuth 2.0 Access Token request to obtain `OAuth2AccessToken` if the client has not yet been authorized
  47. ** `authorization_code`: Triggers the Authorization Request redirect to initiate the flow
  48. ** `client_credentials`: The access token is obtained directly from the Token Endpoint
  49. ** `password`: The access token is obtained directly from the Token Endpoint
  50. ** Additional grant types are supported by xref:servlet/oauth2/index.adoc#oauth2-client-enable-extension-grant-type[enabling extension grant types]
  51. * If an existing `OAuth2AccessToken` is expired, it is refreshed (or renewed)
  52. The following example uses the default `OAuth2AuthorizedClientManager` to configure a `RestClient` capable of accessing protected resources by placing `Bearer` tokens in the `Authorization` header of each request:
  53. .Configure `RestClient` with `ClientHttpRequestInterceptor`
  54. [tabs]
  55. =====
  56. Java::
  57. +
  58. [source,java,role="primary"]
  59. ----
  60. @Configuration
  61. public class RestClientConfig {
  62. @Bean
  63. public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  64. OAuth2ClientHttpRequestInterceptor requestInterceptor =
  65. new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
  66. return RestClient.builder()
  67. .requestInterceptor(requestInterceptor)
  68. .build();
  69. }
  70. }
  71. ----
  72. Kotlin::
  73. +
  74. [source,kotlin,role="secondary"]
  75. ----
  76. @Configuration
  77. class RestClientConfig {
  78. @Bean
  79. fun restClient(authorizedClientManager: OAuth2AuthorizedClientManager): RestClient {
  80. val requestInterceptor = OAuth2ClientHttpRequestInterceptor(authorizedClientManager)
  81. return RestClient.builder()
  82. .requestInterceptor(requestInterceptor)
  83. .build()
  84. }
  85. }
  86. ----
  87. =====
  88. [[oauth2-client-rest-client-registration-id]]
  89. === Providing the `clientRegistrationId`
  90. `OAuth2ClientHttpRequestInterceptor` uses a `ClientRegistrationIdResolver` to determine which client is used to obtain an access token.
  91. By default, `RequestAttributeClientRegistrationIdResolver` is used to resolve the `clientRegistrationId` from `HttpRequest#attributes()`.
  92. The following example demonstrates providing a `clientRegistrationId` via attributes:
  93. .Provide `clientRegistrationId` via attributes
  94. [tabs]
  95. ======
  96. Java::
  97. +
  98. [source,java,role="primary"]
  99. ----
  100. import static org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver.clientRegistrationId;
  101. @Controller
  102. public class ResourceController {
  103. private final RestClient restClient;
  104. public ResourceController(RestClient restClient) {
  105. this.restClient = restClient;
  106. }
  107. @GetMapping("/")
  108. public String index() {
  109. String resourceUri = "...";
  110. String body = this.restClient.get()
  111. .uri(resourceUri)
  112. .attributes(clientRegistrationId("okta")) // <1>
  113. .retrieve()
  114. .body(String.class);
  115. // ...
  116. return "index";
  117. }
  118. }
  119. ----
  120. Kotlin::
  121. +
  122. [source,kotlin,role="secondary"]
  123. ----
  124. import org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver.clientRegistrationId
  125. import org.springframework.web.client.body
  126. @Controller
  127. class ResourceController(private restClient: RestClient) {
  128. @GetMapping("/")
  129. fun index(): String {
  130. val resourceUri = "..."
  131. val body: String = restClient.get()
  132. .uri(resourceUri)
  133. .attributes(clientRegistrationId("okta")) // <1>
  134. .retrieve()
  135. .body<String>()
  136. // ...
  137. return "index"
  138. }
  139. }
  140. ----
  141. ======
  142. <1> `clientRegistrationId()` is a `static` method in `RequestAttributeClientRegistrationIdResolver`.
  143. Alternatively, a custom `ClientRegistrationIdResolver` can be provided.
  144. The following example configures a custom implementation that resolves the `clientRegistrationId` from the current user.
  145. .Configure `ClientHttpRequestInterceptor` with custom `ClientRegistrationIdResolver`
  146. [tabs]
  147. =====
  148. Java::
  149. +
  150. [source,java,role="primary"]
  151. ----
  152. @Configuration
  153. public class RestClientConfig {
  154. @Bean
  155. public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  156. OAuth2ClientHttpRequestInterceptor requestInterceptor =
  157. new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
  158. requestInterceptor.setClientRegistrationIdResolver(clientRegistrationIdResolver());
  159. return RestClient.builder()
  160. .requestInterceptor(requestInterceptor)
  161. .build();
  162. }
  163. private static ClientRegistrationIdResolver clientRegistrationIdResolver() {
  164. return (request) -> {
  165. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  166. return (authentication instanceof OAuth2AuthenticationToken principal)
  167. ? principal.getAuthorizedClientRegistrationId() : null;
  168. };
  169. }
  170. }
  171. ----
  172. Kotlin::
  173. +
  174. [source,kotlin,role="secondary"]
  175. ----
  176. @Configuration
  177. class RestClientConfig {
  178. @Bean
  179. fun restClient(authorizedClientManager: OAuth2AuthorizedClientManager): RestClient {
  180. val requestInterceptor = OAuth2ClientHttpRequestInterceptor(authorizedClientManager)
  181. requestInterceptor.setClientRegistrationIdResolver(clientRegistrationIdResolver())
  182. return RestClient.builder()
  183. .requestInterceptor(requestInterceptor)
  184. .build()
  185. }
  186. fun clientRegistrationIdResolver(): ClientRegistrationIdResolver {
  187. return ClientRegistrationIdResolver { request ->
  188. val authentication = SecurityContextHolder.getContext().getAuthentication()
  189. return if (authentication instanceof OAuth2AuthenticationToken) {
  190. authentication.getAuthorizedClientRegistrationId()
  191. } else {
  192. null
  193. }
  194. }
  195. }
  196. }
  197. ----
  198. =====
  199. [[oauth2-client-rest-client-principal]]
  200. === Providing the `principal`
  201. `OAuth2ClientHttpRequestInterceptor` uses a `PrincipalResolver` to determine which principal name is associated with the access token, which allows an application to choose how to scope the `OAuth2AuthorizedClient` that is stored.
  202. By default, `SecurityContextHolderPrincipalResolver` is used to resolve the current `principal` from the `SecurityContextHolder`.
  203. Alternatively, the `principal` can be resolved from `HttpRequest#attributes()` by configuring `RequestAttributePrincipalResolver`, as the following example shows:
  204. .Configure `ClientHttpRequestInterceptor` with `RequestAttributePrincipalResolver`
  205. [tabs]
  206. =====
  207. Java::
  208. +
  209. [source,java,role="primary"]
  210. ----
  211. @Configuration
  212. public class RestClientConfig {
  213. @Bean
  214. public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  215. OAuth2ClientHttpRequestInterceptor requestInterceptor =
  216. new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
  217. requestInterceptor.setPrincipalResolver(new RequestAttributePrincipalResolver());
  218. return RestClient.builder()
  219. .requestInterceptor(requestInterceptor)
  220. .build();
  221. }
  222. }
  223. ----
  224. Kotlin::
  225. +
  226. [source,kotlin,role="secondary"]
  227. ----
  228. @Configuration
  229. class RestClientConfig {
  230. @Bean
  231. fun restClient(authorizedClientManager: OAuth2AuthorizedClientManager): RestClient {
  232. val requestInterceptor = OAuth2ClientHttpRequestInterceptor(authorizedClientManager)
  233. requestInterceptor.setPrincipalResolver(RequestAttributePrincipalResolver())
  234. return RestClient.builder()
  235. .requestInterceptor(requestInterceptor)
  236. .build()
  237. }
  238. }
  239. ----
  240. =====
  241. The following example demonstrates providing a `principal` name via attributes that scopes the `OAuth2AuthorizedClient` to the application instead of the current user:
  242. .Provide `principal` name via attributes
  243. [tabs]
  244. ======
  245. Java::
  246. +
  247. [source,java,role="primary"]
  248. ----
  249. import static org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver.clientRegistrationId;
  250. import static org.springframework.security.oauth2.client.web.client.RequestAttributePrincipalResolver.principal;
  251. @Controller
  252. public class ResourceController {
  253. private final RestClient restClient;
  254. public ResourceController(RestClient restClient) {
  255. this.restClient = restClient;
  256. }
  257. @GetMapping("/")
  258. public String index() {
  259. String resourceUri = "...";
  260. String body = this.restClient.get()
  261. .uri(resourceUri)
  262. .attributes(clientRegistrationId("okta"))
  263. .attributes(principal("my-application")) // <1>
  264. .retrieve()
  265. .body(String.class);
  266. // ...
  267. return "index";
  268. }
  269. }
  270. ----
  271. Kotlin::
  272. +
  273. [source,kotlin,role="secondary"]
  274. ----
  275. import org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver.clientRegistrationId
  276. import org.springframework.security.oauth2.client.web.client.RequestAttributePrincipalResolver.principal
  277. import org.springframework.web.client.body
  278. @Controller
  279. class ResourceController(private restClient: RestClient) {
  280. @GetMapping("/")
  281. fun index(): String {
  282. val resourceUri = "..."
  283. val body: String = restClient.get()
  284. .uri(resourceUri)
  285. .attributes(clientRegistrationId("okta"))
  286. .attributes(principal("my-application")) // <1>
  287. .retrieve()
  288. .body<String>()
  289. // ...
  290. return "index"
  291. }
  292. }
  293. ----
  294. ======
  295. <1> `principal()` is a `static` method in `RequestAttributePrincipalResolver`.
  296. [[oauth2-client-rest-client-authorization-failure-handler]]
  297. === Handling Failure
  298. If an access token is invalid for any reason (e.g. expired token), it can be beneficial to handle the failure by removing the access token so that it cannot be used again.
  299. You can set up the interceptor to do this automatically by providing an `OAuth2AuthorizationFailureHandler` to remove the access token.
  300. The following example uses an `OAuth2AuthorizedClientRepository` to set up an `OAuth2AuthorizationFailureHandler` that removes an invalid `OAuth2AuthorizedClient` *within* the context of an `HttpServletRequest`:
  301. .Configure `OAuth2AuthorizationFailureHandler` using `OAuth2AuthorizedClientRepository`
  302. [tabs]
  303. =====
  304. Java::
  305. +
  306. [source,java,role="primary"]
  307. ----
  308. @Configuration
  309. public class RestClientConfig {
  310. @Bean
  311. public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager,
  312. OAuth2AuthorizedClientRepository authorizedClientRepository) {
  313. OAuth2ClientHttpRequestInterceptor requestInterceptor =
  314. new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
  315. OAuth2AuthorizationFailureHandler authorizationFailureHandler =
  316. OAuth2ClientHttpRequestInterceptor.authorizationFailureHandler(authorizedClientRepository);
  317. requestInterceptor.setAuthorizationFailureHandler(authorizationFailureHandler);
  318. return RestClient.builder()
  319. .requestInterceptor(requestInterceptor)
  320. .build();
  321. }
  322. }
  323. ----
  324. Kotlin::
  325. +
  326. [source,kotlin,role="secondary"]
  327. ----
  328. @Configuration
  329. class RestClientConfig {
  330. @Bean
  331. fun restClient(authorizedClientManager: OAuth2AuthorizedClientManager,
  332. authorizedClientRepository: OAuth2AuthorizedClientRepository): RestClient {
  333. val requestInterceptor = OAuth2ClientHttpRequestInterceptor(authorizedClientManager)
  334. val authorizationFailureHandler = OAuth2ClientHttpRequestInterceptor
  335. .authorizationFailureHandler(authorizedClientRepository)
  336. requestInterceptor.setAuthorizationFailureHandler(authorizationFailureHandler)
  337. return RestClient.builder()
  338. .requestInterceptor(requestInterceptor)
  339. .build()
  340. }
  341. }
  342. ----
  343. =====
  344. Alternatively, an `OAuth2AuthorizedClientService` can be used to remove an invalid `OAuth2AuthorizedClient` *outside* the context of an `HttpServletRequest`, as the following example shows:
  345. .Configure `OAuth2AuthorizationFailureHandler` using `OAuth2AuthorizedClientService`
  346. [tabs]
  347. =====
  348. Java::
  349. +
  350. [source,java,role="primary"]
  351. ----
  352. @Configuration
  353. public class RestClientConfig {
  354. @Bean
  355. public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager,
  356. OAuth2AuthorizedClientService authorizedClientService) {
  357. OAuth2ClientHttpRequestInterceptor requestInterceptor =
  358. new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
  359. OAuth2AuthorizationFailureHandler authorizationFailureHandler =
  360. OAuth2ClientHttpRequestInterceptor.authorizationFailureHandler(authorizedClientService);
  361. requestInterceptor.setAuthorizationFailureHandler(authorizationFailureHandler);
  362. return RestClient.builder()
  363. .requestInterceptor(requestInterceptor)
  364. .build();
  365. }
  366. }
  367. ----
  368. Kotlin::
  369. +
  370. [source,kotlin,role="secondary"]
  371. ----
  372. @Configuration
  373. class RestClientConfig {
  374. @Bean
  375. fun restClient(authorizedClientManager: OAuth2AuthorizedClientManager,
  376. authorizedClientService: OAuth2AuthorizedClientService): RestClient {
  377. val requestInterceptor = OAuth2ClientHttpRequestInterceptor(authorizedClientManager)
  378. val authorizationFailureHandler = OAuth2ClientHttpRequestInterceptor
  379. .authorizationFailureHandler(authorizedClientService)
  380. requestInterceptor.setAuthorizationFailureHandler(authorizationFailureHandler)
  381. return RestClient.builder()
  382. .requestInterceptor(requestInterceptor)
  383. .build()
  384. }
  385. }
  386. ----
  387. =====
  388. [[oauth2-client-web-client]]
  389. == [[oauth2Client-webclient-servlet]]WebClient Integration for Servlet Environments
  390. The OAuth 2.0 Client support integrates with `WebClient` by using an `ExchangeFilterFunction`.
  391. The `ServletOAuth2AuthorizedClientExchangeFilterFunction` provides a mechanism for requesting protected resources by using an `OAuth2AuthorizedClient` and including the associated `OAuth2AccessToken` as a Bearer Token.
  392. It directly uses an xref:servlet/oauth2/client/core.adoc#oauth2Client-authorized-manager-provider[`OAuth2AuthorizedClientManager`] and, therefore, inherits the following capabilities:
  393. * An `OAuth2AccessToken` is requested if the client has not yet been authorized.
  394. ** `authorization_code`: Triggers the Authorization Request redirect to initiate the flow.
  395. ** `client_credentials`: The access token is obtained directly from the Token Endpoint.
  396. ** `password`: The access token is obtained directly from the Token Endpoint.
  397. * If the `OAuth2AccessToken` is expired, it is refreshed (or renewed) if an `OAuth2AuthorizedClientProvider` is available to perform the authorization
  398. The following code shows an example of how to configure `WebClient` with OAuth 2.0 Client support:
  399. [tabs]
  400. ======
  401. Java::
  402. +
  403. [source,java,role="primary"]
  404. ----
  405. @Bean
  406. WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  407. ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
  408. new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
  409. return WebClient.builder()
  410. .apply(oauth2Client.oauth2Configuration())
  411. .build();
  412. }
  413. ----
  414. Kotlin::
  415. +
  416. [source,kotlin,role="secondary"]
  417. ----
  418. @Bean
  419. fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient {
  420. val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager)
  421. return WebClient.builder()
  422. .apply(oauth2Client.oauth2Configuration())
  423. .build()
  424. }
  425. ----
  426. ======
  427. [[oauth2-client-web-client-authorized-client]]
  428. === Providing the Authorized Client
  429. The `ServletOAuth2AuthorizedClientExchangeFilterFunction` determines the client to use (for a request) by resolving the `OAuth2AuthorizedClient` from the `ClientRequest.attributes()` (request attributes).
  430. The following code shows how to set an `OAuth2AuthorizedClient` as a request attribute:
  431. [tabs]
  432. ======
  433. Java::
  434. +
  435. [source,java,role="primary"]
  436. ----
  437. @GetMapping("/")
  438. public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) {
  439. String resourceUri = ...
  440. String body = webClient
  441. .get()
  442. .uri(resourceUri)
  443. .attributes(oauth2AuthorizedClient(authorizedClient)) <1>
  444. .retrieve()
  445. .bodyToMono(String.class)
  446. .block();
  447. ...
  448. return "index";
  449. }
  450. ----
  451. Kotlin::
  452. +
  453. [source,kotlin,role="secondary"]
  454. ----
  455. @GetMapping("/")
  456. fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String {
  457. val resourceUri: String = ...
  458. val body: String = webClient
  459. .get()
  460. .uri(resourceUri)
  461. .attributes(oauth2AuthorizedClient(authorizedClient)) <1>
  462. .retrieve()
  463. .bodyToMono()
  464. .block()
  465. ...
  466. return "index"
  467. }
  468. ----
  469. ======
  470. <1> `oauth2AuthorizedClient()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`.
  471. The following code shows how to set the `ClientRegistration.getRegistrationId()` as a request attribute:
  472. [tabs]
  473. ======
  474. Java::
  475. +
  476. [source,java,role="primary"]
  477. ----
  478. @GetMapping("/")
  479. public String index() {
  480. String resourceUri = ...
  481. String body = webClient
  482. .get()
  483. .uri(resourceUri)
  484. .attributes(clientRegistrationId("okta")) <1>
  485. .retrieve()
  486. .bodyToMono(String.class)
  487. .block();
  488. ...
  489. return "index";
  490. }
  491. ----
  492. Kotlin::
  493. +
  494. [source,kotlin,role="secondary"]
  495. ----
  496. @GetMapping("/")
  497. fun index(): String {
  498. val resourceUri: String = ...
  499. val body: String = webClient
  500. .get()
  501. .uri(resourceUri)
  502. .attributes(clientRegistrationId("okta")) <1>
  503. .retrieve()
  504. .bodyToMono()
  505. .block()
  506. ...
  507. return "index"
  508. }
  509. ----
  510. ======
  511. <1> `clientRegistrationId()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`.
  512. The following code shows how to set an `Authentication` as a request attribute:
  513. [tabs]
  514. ======
  515. Java::
  516. +
  517. [source,java,role="primary"]
  518. ----
  519. @GetMapping("/")
  520. public String index() {
  521. String resourceUri = ...
  522. Authentication anonymousAuthentication = new AnonymousAuthenticationToken(
  523. "anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
  524. String body = webClient
  525. .get()
  526. .uri(resourceUri)
  527. .attributes(authentication(anonymousAuthentication)) <1>
  528. .retrieve()
  529. .bodyToMono(String.class)
  530. .block();
  531. ...
  532. return "index";
  533. }
  534. ----
  535. Kotlin::
  536. +
  537. [source,kotlin,role="secondary"]
  538. ----
  539. @GetMapping("/")
  540. fun index(): String {
  541. val resourceUri: String = ...
  542. val anonymousAuthentication: Authentication = AnonymousAuthenticationToken(
  543. "anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))
  544. val body: String = webClient
  545. .get()
  546. .uri(resourceUri)
  547. .attributes(authentication(anonymousAuthentication)) <1>
  548. .retrieve()
  549. .bodyToMono()
  550. .block()
  551. ...
  552. return "index"
  553. }
  554. ----
  555. ======
  556. <1> `authentication()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`.
  557. [WARNING]
  558. ====
  559. It is recommended to be cautious with this feature since all HTTP requests will receive an access token bound to the provided principal.
  560. ====
  561. [[oauth2-client-web-client-default-authorized-client]]
  562. === Defaulting the Authorized Client
  563. If neither `OAuth2AuthorizedClient` or `ClientRegistration.getRegistrationId()` is provided as a request attribute, the `ServletOAuth2AuthorizedClientExchangeFilterFunction` can determine the _default_ client to use, depending on its configuration.
  564. If `setDefaultOAuth2AuthorizedClient(true)` is configured and the user has authenticated by using `HttpSecurity.oauth2Login()`, the `OAuth2AccessToken` associated with the current `OAuth2AuthenticationToken` is used.
  565. The following code shows the specific configuration:
  566. [tabs]
  567. ======
  568. Java::
  569. +
  570. [source,java,role="primary"]
  571. ----
  572. @Bean
  573. WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  574. ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
  575. new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
  576. oauth2Client.setDefaultOAuth2AuthorizedClient(true);
  577. return WebClient.builder()
  578. .apply(oauth2Client.oauth2Configuration())
  579. .build();
  580. }
  581. ----
  582. Kotlin::
  583. +
  584. [source,kotlin,role="secondary"]
  585. ----
  586. @Bean
  587. fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient {
  588. val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager)
  589. oauth2Client.setDefaultOAuth2AuthorizedClient(true)
  590. return WebClient.builder()
  591. .apply(oauth2Client.oauth2Configuration())
  592. .build()
  593. }
  594. ----
  595. ======
  596. [WARNING]
  597. ====
  598. Be cautious with this feature, since all HTTP requests receive the access token.
  599. ====
  600. Alternatively, if `setDefaultClientRegistrationId("okta")` is configured with a valid `ClientRegistration`, the `OAuth2AccessToken` associated with the `OAuth2AuthorizedClient` is used.
  601. The following code shows the specific configuration:
  602. [tabs]
  603. ======
  604. Java::
  605. +
  606. [source,java,role="primary"]
  607. ----
  608. @Bean
  609. WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  610. ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
  611. new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
  612. oauth2Client.setDefaultClientRegistrationId("okta");
  613. return WebClient.builder()
  614. .apply(oauth2Client.oauth2Configuration())
  615. .build();
  616. }
  617. ----
  618. Kotlin::
  619. +
  620. [source,kotlin,role="secondary"]
  621. ----
  622. @Bean
  623. fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient {
  624. val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager)
  625. oauth2Client.setDefaultClientRegistrationId("okta")
  626. return WebClient.builder()
  627. .apply(oauth2Client.oauth2Configuration())
  628. .build()
  629. }
  630. ----
  631. ======
  632. [WARNING]
  633. ====
  634. Be cautious with this feature, since all HTTP requests receive the access token.
  635. ====