authorization-grants.adoc 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. [[oauth2Client-auth-grant-support]]
  2. = Authorization Grant Support
  3. [[oauth2Client-auth-code-grant]]
  4. == Authorization Code
  5. [NOTE]
  6. Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] grant.
  7. === Obtaining Authorization
  8. [NOTE]
  9. Please refer to the https://tools.ietf.org/html/rfc6749#section-4.1.1[Authorization Request/Response] protocol flow for the Authorization Code grant.
  10. === Initiating the Authorization Request
  11. The `OAuth2AuthorizationRequestRedirectWebFilter` uses a `ServerOAuth2AuthorizationRequestResolver` to resolve an `OAuth2AuthorizationRequest` and initiate the Authorization Code grant flow by redirecting the end-user's user-agent to the Authorization Server's Authorization Endpoint.
  12. The primary role of the `ServerOAuth2AuthorizationRequestResolver` is to resolve an `OAuth2AuthorizationRequest` from the provided web request.
  13. The default implementation `DefaultServerOAuth2AuthorizationRequestResolver` matches on the (default) path `+/oauth2/authorization/{registrationId}+` extracting the `registrationId` and using it to build the `OAuth2AuthorizationRequest` for the associated `ClientRegistration`.
  14. Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:
  15. [source,yaml,attrs="-attributes"]
  16. ----
  17. spring:
  18. security:
  19. oauth2:
  20. client:
  21. registration:
  22. okta:
  23. client-id: okta-client-id
  24. client-secret: okta-client-secret
  25. authorization-grant-type: authorization_code
  26. redirect-uri: "{baseUrl}/authorized/okta"
  27. scope: read, write
  28. provider:
  29. okta:
  30. authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize
  31. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  32. ----
  33. A request with the base path `/oauth2/authorization/okta` will initiate the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectWebFilter` and ultimately start the Authorization Code grant flow.
  34. [NOTE]
  35. The `AuthorizationCodeReactiveOAuth2AuthorizedClientProvider` is an implementation of `ReactiveOAuth2AuthorizedClientProvider` for the Authorization Code grant,
  36. which also initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectWebFilter`.
  37. If the OAuth 2.0 Client is a https://tools.ietf.org/html/rfc6749#section-2.1[Public Client], then configure the OAuth 2.0 Client registration as follows:
  38. [source,yaml,attrs="-attributes"]
  39. ----
  40. spring:
  41. security:
  42. oauth2:
  43. client:
  44. registration:
  45. okta:
  46. client-id: okta-client-id
  47. client-authentication-method: none
  48. authorization-grant-type: authorization_code
  49. redirect-uri: "{baseUrl}/authorized/okta"
  50. ...
  51. ----
  52. Public Clients are supported using https://tools.ietf.org/html/rfc7636[Proof Key for Code Exchange] (PKCE).
  53. If the client is running in an untrusted environment (eg. native application or web browser-based application) and therefore incapable of maintaining the confidentiality of it's credentials, PKCE will automatically be used when the following conditions are true:
  54. . `client-secret` is omitted (or empty)
  55. . `client-authentication-method` is set to "none" (`ClientAuthenticationMethod.NONE`)
  56. [TIP]
  57. If the OAuth 2.0 Provider supports PKCE for https://tools.ietf.org/html/rfc6749#section-2.1[Confidential Clients], you may (optionally) configure it using `DefaultServerOAuth2AuthorizationRequestResolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce())`.
  58. [[oauth2Client-auth-code-redirect-uri]]
  59. The `DefaultServerOAuth2AuthorizationRequestResolver` also supports `URI` template variables for the `redirect-uri` using `UriComponentsBuilder`.
  60. The following configuration uses all the supported `URI` template variables:
  61. [source,yaml,attrs="-attributes"]
  62. ----
  63. spring:
  64. security:
  65. oauth2:
  66. client:
  67. registration:
  68. okta:
  69. ...
  70. redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}"
  71. ...
  72. ----
  73. [NOTE]
  74. `+{baseUrl}+` resolves to `+{baseScheme}://{baseHost}{basePort}{basePath}+`
  75. Configuring the `redirect-uri` with `URI` template variables is especially useful when the OAuth 2.0 Client is running behind a xref:features/exploits/http.adoc#http-proxy-server[Proxy Server].
  76. This ensures that the `X-Forwarded-*` headers are used when expanding the `redirect-uri`.
  77. === Customizing the Authorization Request
  78. One of the primary use cases a `ServerOAuth2AuthorizationRequestResolver` can realize is the ability to customize the Authorization Request with additional parameters above the standard parameters defined in the OAuth 2.0 Authorization Framework.
  79. For example, OpenID Connect defines additional OAuth 2.0 request parameters for the https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest[Authorization Code Flow] extending from the standard parameters defined in the https://tools.ietf.org/html/rfc6749#section-4.1.1[OAuth 2.0 Authorization Framework].
  80. One of those extended parameters is the `prompt` parameter.
  81. [NOTE]
  82. OPTIONAL. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent. The defined values are: none, login, consent, select_account
  83. The following example shows how to configure the `DefaultServerOAuth2AuthorizationRequestResolver` with a `Consumer<OAuth2AuthorizationRequest.Builder>` that customizes the Authorization Request for `oauth2Login()`, by including the request parameter `prompt=consent`.
  84. [tabs]
  85. ======
  86. Java::
  87. +
  88. [source,java,role="primary"]
  89. ----
  90. @EnableWebFluxSecurity
  91. public class OAuth2LoginSecurityConfig {
  92. @Autowired
  93. private ReactiveClientRegistrationRepository clientRegistrationRepository;
  94. @Bean
  95. public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
  96. http
  97. .authorizeExchange(authorize -> authorize
  98. .anyExchange().authenticated()
  99. )
  100. .oauth2Login(oauth2 -> oauth2
  101. .authorizationRequestResolver(
  102. authorizationRequestResolver(this.clientRegistrationRepository)
  103. )
  104. );
  105. return http.build();
  106. }
  107. private ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver(
  108. ReactiveClientRegistrationRepository clientRegistrationRepository) {
  109. DefaultServerOAuth2AuthorizationRequestResolver authorizationRequestResolver =
  110. new DefaultServerOAuth2AuthorizationRequestResolver(
  111. clientRegistrationRepository);
  112. authorizationRequestResolver.setAuthorizationRequestCustomizer(
  113. authorizationRequestCustomizer());
  114. return authorizationRequestResolver;
  115. }
  116. private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
  117. return customizer -> customizer
  118. .additionalParameters(params -> params.put("prompt", "consent"));
  119. }
  120. }
  121. ----
  122. Kotlin::
  123. +
  124. [source,kotlin,role="secondary"]
  125. ----
  126. @EnableWebFluxSecurity
  127. class SecurityConfig {
  128. @Autowired
  129. private lateinit var customClientRegistrationRepository: ReactiveClientRegistrationRepository
  130. @Bean
  131. fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  132. return http {
  133. authorizeExchange {
  134. authorize(anyExchange, authenticated)
  135. }
  136. oauth2Login {
  137. authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
  138. }
  139. }
  140. }
  141. private fun authorizationRequestResolver(
  142. clientRegistrationRepository: ReactiveClientRegistrationRepository): ServerOAuth2AuthorizationRequestResolver {
  143. val authorizationRequestResolver = DefaultServerOAuth2AuthorizationRequestResolver(
  144. clientRegistrationRepository)
  145. authorizationRequestResolver.setAuthorizationRequestCustomizer(
  146. authorizationRequestCustomizer())
  147. return authorizationRequestResolver
  148. }
  149. private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
  150. return Consumer { customizer ->
  151. customizer
  152. .additionalParameters { params -> params["prompt"] = "consent" }
  153. }
  154. }
  155. }
  156. ----
  157. ======
  158. For the simple use case, where the additional request parameter is always the same for a specific provider, it may be added directly in the `authorization-uri` property.
  159. For example, if the value for the request parameter `prompt` is always `consent` for the provider `okta`, than simply configure as follows:
  160. [source,yaml]
  161. ----
  162. spring:
  163. security:
  164. oauth2:
  165. client:
  166. provider:
  167. okta:
  168. authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent
  169. ----
  170. The preceding example shows the common use case of adding a custom parameter on top of the standard parameters.
  171. Alternatively, if your requirements are more advanced, you can take full control in building the Authorization Request URI by simply overriding the `OAuth2AuthorizationRequest.authorizationRequestUri` property.
  172. [TIP]
  173. `OAuth2AuthorizationRequest.Builder.build()` constructs the `OAuth2AuthorizationRequest.authorizationRequestUri`, which represents the Authorization Request URI including all query parameters using the `application/x-www-form-urlencoded` format.
  174. The following example shows a variation of `authorizationRequestCustomizer()` from the preceding example, and instead overrides the `OAuth2AuthorizationRequest.authorizationRequestUri` property.
  175. [tabs]
  176. ======
  177. Java::
  178. +
  179. [source,java,role="primary"]
  180. ----
  181. private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
  182. return customizer -> customizer
  183. .authorizationRequestUri(uriBuilder -> uriBuilder
  184. .queryParam("prompt", "consent").build());
  185. }
  186. ----
  187. Kotlin::
  188. +
  189. [source,kotlin,role="secondary"]
  190. ----
  191. private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
  192. return Consumer { customizer: OAuth2AuthorizationRequest.Builder ->
  193. customizer
  194. .authorizationRequestUri { uriBuilder: UriBuilder ->
  195. uriBuilder
  196. .queryParam("prompt", "consent").build()
  197. }
  198. }
  199. }
  200. ----
  201. ======
  202. === Storing the Authorization Request
  203. The `ServerAuthorizationRequestRepository` is responsible for the persistence of the `OAuth2AuthorizationRequest` from the time the Authorization Request is initiated to the time the Authorization Response is received (the callback).
  204. [TIP]
  205. The `OAuth2AuthorizationRequest` is used to correlate and validate the Authorization Response.
  206. The default implementation of `ServerAuthorizationRequestRepository` is `WebSessionOAuth2ServerAuthorizationRequestRepository`, which stores the `OAuth2AuthorizationRequest` in the `WebSession`.
  207. If you have a custom implementation of `ServerAuthorizationRequestRepository`, you may configure it as shown in the following example:
  208. .ServerAuthorizationRequestRepository Configuration
  209. [tabs]
  210. ======
  211. Java::
  212. +
  213. [source,java,role="primary"]
  214. ----
  215. @EnableWebFluxSecurity
  216. public class OAuth2ClientSecurityConfig {
  217. @Bean
  218. public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
  219. http
  220. .oauth2Client(oauth2 -> oauth2
  221. .authorizationRequestRepository(this.authorizationRequestRepository())
  222. ...
  223. );
  224. return http.build();
  225. }
  226. }
  227. ----
  228. Kotlin::
  229. +
  230. [source,kotlin,role="secondary"]
  231. ----
  232. @EnableWebFluxSecurity
  233. class OAuth2ClientSecurityConfig {
  234. @Bean
  235. fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  236. return http {
  237. oauth2Client {
  238. authorizationRequestRepository = authorizationRequestRepository()
  239. }
  240. }
  241. }
  242. }
  243. ----
  244. ======
  245. === Requesting an Access Token
  246. [NOTE]
  247. Please refer to the https://tools.ietf.org/html/rfc6749#section-4.1.3[Access Token Request/Response] protocol flow for the Authorization Code grant.
  248. The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the Authorization Code grant is `WebClientReactiveAuthorizationCodeTokenResponseClient`, which uses a `WebClient` for exchanging an authorization code for an access token at the Authorization Server’s Token Endpoint.
  249. The `WebClientReactiveAuthorizationCodeTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.
  250. === Customizing the Access Token Request
  251. If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveAuthorizationCodeTokenResponseClient.setParametersConverter()` with a custom `Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>`.
  252. The default implementation builds a `MultiValueMap<String, String>` containing only the `grant_type` parameter of a standard https://tools.ietf.org/html/rfc6749#section-4.1.3[OAuth 2.0 Access Token Request] which is used to construct the request. Other parameters required by the Authorization Code grant are added directly to the body of the request by the `WebClientReactiveAuthorizationCodeTokenResponseClient`.
  253. However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s).
  254. [TIP]
  255. If you prefer to only add additional parameters, you can instead provide `WebClientReactiveAuthorizationCodeTokenResponseClient.addParametersConverter()` with a custom `Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>` which constructs an aggregate `Converter`.
  256. IMPORTANT: The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.
  257. === Customizing the Access Token Response
  258. On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveAuthorizationCodeTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`.
  259. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly.
  260. === Customizing the `WebClient`
  261. Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveAuthorizationCodeTokenResponseClient.setWebClient()` with a custom configured `WebClient`.
  262. Whether you customize `WebClientReactiveAuthorizationCodeTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example:
  263. .Access Token Response Configuration
  264. [tabs]
  265. ======
  266. Java::
  267. +
  268. [source,java,role="primary"]
  269. ----
  270. @EnableWebFluxSecurity
  271. public class OAuth2ClientSecurityConfig {
  272. @Bean
  273. public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
  274. http
  275. .oauth2Client(oauth2 -> oauth2
  276. .authenticationManager(this.authorizationCodeAuthenticationManager())
  277. ...
  278. );
  279. return http.build();
  280. }
  281. private ReactiveAuthenticationManager authorizationCodeAuthenticationManager() {
  282. WebClientReactiveAuthorizationCodeTokenResponseClient accessTokenResponseClient =
  283. new WebClientReactiveAuthorizationCodeTokenResponseClient();
  284. ...
  285. return new OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient);
  286. }
  287. }
  288. ----
  289. Kotlin::
  290. +
  291. [source,kotlin,role="secondary"]
  292. ----
  293. @EnableWebFluxSecurity
  294. class OAuth2ClientSecurityConfig {
  295. @Bean
  296. fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  297. return http {
  298. oauth2Client {
  299. authenticationManager = authorizationCodeAuthenticationManager()
  300. }
  301. }
  302. }
  303. private fun authorizationCodeAuthenticationManager(): ReactiveAuthenticationManager {
  304. val accessTokenResponseClient = WebClientReactiveAuthorizationCodeTokenResponseClient()
  305. ...
  306. return OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient)
  307. }
  308. }
  309. ----
  310. ======
  311. [[oauth2Client-refresh-token-grant]]
  312. == Refresh Token
  313. [NOTE]
  314. Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.5[Refresh Token].
  315. === Refreshing an Access Token
  316. [NOTE]
  317. Please refer to the https://tools.ietf.org/html/rfc6749#section-6[Access Token Request/Response] protocol flow for the Refresh Token grant.
  318. The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the Refresh Token grant is `WebClientReactiveRefreshTokenTokenResponseClient`, which uses a `WebClient` when refreshing an access token at the Authorization Server’s Token Endpoint.
  319. The `WebClientReactiveRefreshTokenTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.
  320. === Customizing the Access Token Request
  321. If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveRefreshTokenTokenResponseClient.setParametersConverter()` with a custom `Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>`.
  322. The default implementation builds a `MultiValueMap<String, String>` containing only the `grant_type` parameter of a standard https://tools.ietf.org/html/rfc6749#section-6[OAuth 2.0 Access Token Request] which is used to construct the request. Other parameters required by the Refresh Token grant are added directly to the body of the request by the `WebClientReactiveRefreshTokenTokenResponseClient`.
  323. However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s).
  324. [TIP]
  325. If you prefer to only add additional parameters, you can instead provide `WebClientReactiveRefreshTokenTokenResponseClient.addParametersConverter()` with a custom `Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>` which constructs an aggregate `Converter`.
  326. IMPORTANT: The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.
  327. === Customizing the Access Token Response
  328. On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveRefreshTokenTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`.
  329. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly.
  330. === Customizing the `WebClient`
  331. Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveRefreshTokenTokenResponseClient.setWebClient()` with a custom configured `WebClient`.
  332. Whether you customize `WebClientReactiveRefreshTokenTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example:
  333. .Access Token Response Configuration
  334. [tabs]
  335. ======
  336. Java::
  337. +
  338. [source,java,role="primary"]
  339. ----
  340. // Customize
  341. ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient = ...
  342. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  343. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  344. .authorizationCode()
  345. .refreshToken(configurer -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
  346. .build();
  347. ...
  348. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  349. ----
  350. Kotlin::
  351. +
  352. [source,kotlin,role="secondary"]
  353. ----
  354. // Customize
  355. val refreshTokenTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> = ...
  356. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  357. .authorizationCode()
  358. .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
  359. .build()
  360. ...
  361. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  362. ----
  363. ======
  364. [NOTE]
  365. `ReactiveOAuth2AuthorizedClientProviderBuilder.builder().refreshToken()` configures a `RefreshTokenReactiveOAuth2AuthorizedClientProvider`,
  366. which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Refresh Token grant.
  367. The `OAuth2RefreshToken` may optionally be returned in the Access Token Response for the `authorization_code` and `password` grant types.
  368. If the `OAuth2AuthorizedClient.getRefreshToken()` is available and the `OAuth2AuthorizedClient.getAccessToken()` is expired, it will automatically be refreshed by the `RefreshTokenReactiveOAuth2AuthorizedClientProvider`.
  369. [[oauth2Client-client-creds-grant]]
  370. == Client Credentials
  371. [NOTE]
  372. Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] grant.
  373. === Requesting an Access Token
  374. [NOTE]
  375. Please refer to the https://tools.ietf.org/html/rfc6749#section-4.4.2[Access Token Request/Response] protocol flow for the Client Credentials grant.
  376. The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the Client Credentials grant is `WebClientReactiveClientCredentialsTokenResponseClient`, which uses a `WebClient` when requesting an access token at the Authorization Server’s Token Endpoint.
  377. The `WebClientReactiveClientCredentialsTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.
  378. === Customizing the Access Token Request
  379. If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveClientCredentialsTokenResponseClient.setParametersConverter()` with a custom `Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>`.
  380. The default implementation builds a `MultiValueMap<String, String>` containing only the `grant_type` parameter of a standard https://tools.ietf.org/html/rfc6749#section-4.4.2[OAuth 2.0 Access Token Request] which is used to construct the request. Other parameters required by the Client Credentials grant are added directly to the body of the request by the `WebClientReactiveClientCredentialsTokenResponseClient`.
  381. However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s).
  382. [TIP]
  383. If you prefer to only add additional parameters, you can instead provide `WebClientReactiveClientCredentialsTokenResponseClient.addParametersConverter()` with a custom `Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>` which constructs an aggregate `Converter`.
  384. IMPORTANT: The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.
  385. === Customizing the Access Token Response
  386. On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveClientCredentialsTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`.
  387. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly.
  388. === Customizing the `WebClient`
  389. Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveClientCredentialsTokenResponseClient.setWebClient()` with a custom configured `WebClient`.
  390. Whether you customize `WebClientReactiveClientCredentialsTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example:
  391. [tabs]
  392. ======
  393. Java::
  394. +
  395. [source,java,role="primary"]
  396. ----
  397. // Customize
  398. ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = ...
  399. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  400. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  401. .clientCredentials(configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
  402. .build();
  403. ...
  404. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  405. ----
  406. Kotlin::
  407. +
  408. [source,kotlin,role="secondary"]
  409. ----
  410. // Customize
  411. val clientCredentialsTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> = ...
  412. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  413. .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
  414. .build()
  415. ...
  416. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  417. ----
  418. ======
  419. [NOTE]
  420. `ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsReactiveOAuth2AuthorizedClientProvider`,
  421. which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Client Credentials grant.
  422. === Using the Access Token
  423. Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:
  424. [source,yaml]
  425. ----
  426. spring:
  427. security:
  428. oauth2:
  429. client:
  430. registration:
  431. okta:
  432. client-id: okta-client-id
  433. client-secret: okta-client-secret
  434. authorization-grant-type: client_credentials
  435. scope: read, write
  436. provider:
  437. okta:
  438. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  439. ----
  440. ...and the `ReactiveOAuth2AuthorizedClientManager` `@Bean`:
  441. [tabs]
  442. ======
  443. Java::
  444. +
  445. [source,java,role="primary"]
  446. ----
  447. @Bean
  448. public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
  449. ReactiveClientRegistrationRepository clientRegistrationRepository,
  450. ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
  451. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  452. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  453. .clientCredentials()
  454. .build();
  455. DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
  456. new DefaultReactiveOAuth2AuthorizedClientManager(
  457. clientRegistrationRepository, authorizedClientRepository);
  458. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  459. return authorizedClientManager;
  460. }
  461. ----
  462. Kotlin::
  463. +
  464. [source,kotlin,role="secondary"]
  465. ----
  466. @Bean
  467. fun authorizedClientManager(
  468. clientRegistrationRepository: ReactiveClientRegistrationRepository,
  469. authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
  470. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  471. .clientCredentials()
  472. .build()
  473. val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
  474. clientRegistrationRepository, authorizedClientRepository)
  475. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  476. return authorizedClientManager
  477. }
  478. ----
  479. ======
  480. You may obtain the `OAuth2AccessToken` as follows:
  481. [tabs]
  482. ======
  483. Java::
  484. +
  485. [source,java,role="primary"]
  486. ----
  487. @Controller
  488. public class OAuth2ClientController {
  489. @Autowired
  490. private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
  491. @GetMapping("/")
  492. public Mono<String> index(Authentication authentication, ServerWebExchange exchange) {
  493. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  494. .principal(authentication)
  495. .attribute(ServerWebExchange.class.getName(), exchange)
  496. .build();
  497. return this.authorizedClientManager.authorize(authorizeRequest)
  498. .map(OAuth2AuthorizedClient::getAccessToken)
  499. ...
  500. .thenReturn("index");
  501. }
  502. }
  503. ----
  504. Kotlin::
  505. +
  506. [source,kotlin,role="secondary"]
  507. ----
  508. class OAuth2ClientController {
  509. @Autowired
  510. private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager
  511. @GetMapping("/")
  512. fun index(authentication: Authentication, exchange: ServerWebExchange): Mono<String> {
  513. val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  514. .principal(authentication)
  515. .attribute(ServerWebExchange::class.java.name, exchange)
  516. .build()
  517. return authorizedClientManager.authorize(authorizeRequest)
  518. .map { it.accessToken }
  519. ...
  520. .thenReturn("index")
  521. }
  522. }
  523. ----
  524. ======
  525. [NOTE]
  526. `ServerWebExchange` is an OPTIONAL attribute.
  527. If not provided, it will be obtained from the https://projectreactor.io/docs/core/release/reference/#context[Reactor's Context] via the key `ServerWebExchange.class`.
  528. [[oauth2Client-password-grant]]
  529. == Resource Owner Password Credentials
  530. [NOTE]
  531. Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] grant.
  532. === Requesting an Access Token
  533. [NOTE]
  534. Please refer to the https://tools.ietf.org/html/rfc6749#section-4.3.2[Access Token Request/Response] protocol flow for the Resource Owner Password Credentials grant.
  535. The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the Resource Owner Password Credentials grant is `WebClientReactivePasswordTokenResponseClient`, which uses a `WebClient` when requesting an access token at the Authorization Server’s Token Endpoint.
  536. The `WebClientReactivePasswordTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.
  537. === Customizing the Access Token Request
  538. If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactivePasswordTokenResponseClient.setParametersConverter()` with a custom `Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>`.
  539. The default implementation builds a `MultiValueMap<String, String>` containing only the `grant_type` parameter of a standard https://tools.ietf.org/html/rfc6749#section-4.4.2[OAuth 2.0 Access Token Request] which is used to construct the request. Other parameters required by the Resource Owner Password Credentials grant are added directly to the body of the request by the `WebClientReactivePasswordTokenResponseClient`.
  540. However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s).
  541. [TIP]
  542. If you prefer to only add additional parameters, you can instead provide `WebClientReactivePasswordTokenResponseClient.addParametersConverter()` with a custom `Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>` which constructs an aggregate `Converter`.
  543. IMPORTANT: The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.
  544. === Customizing the Access Token Response
  545. On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactivePasswordTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`.
  546. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly.
  547. === Customizing the `WebClient`
  548. Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactivePasswordTokenResponseClient.setWebClient()` with a custom configured `WebClient`.
  549. Whether you customize `WebClientReactivePasswordTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example:
  550. [tabs]
  551. ======
  552. Java::
  553. +
  554. [source,java,role="primary"]
  555. ----
  556. // Customize
  557. ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient = ...
  558. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  559. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  560. .password(configurer -> configurer.accessTokenResponseClient(passwordTokenResponseClient))
  561. .refreshToken()
  562. .build();
  563. ...
  564. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  565. ----
  566. Kotlin::
  567. +
  568. [source,kotlin,role="secondary"]
  569. ----
  570. val passwordTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...
  571. val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  572. .password { it.accessTokenResponseClient(passwordTokenResponseClient) }
  573. .refreshToken()
  574. .build()
  575. ...
  576. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  577. ----
  578. ======
  579. [NOTE]
  580. `ReactiveOAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordReactiveOAuth2AuthorizedClientProvider`,
  581. which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Resource Owner Password Credentials grant.
  582. === Using the Access Token
  583. Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:
  584. [source,yaml]
  585. ----
  586. spring:
  587. security:
  588. oauth2:
  589. client:
  590. registration:
  591. okta:
  592. client-id: okta-client-id
  593. client-secret: okta-client-secret
  594. authorization-grant-type: password
  595. scope: read, write
  596. provider:
  597. okta:
  598. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  599. ----
  600. ...and the `ReactiveOAuth2AuthorizedClientManager` `@Bean`:
  601. [tabs]
  602. ======
  603. Java::
  604. +
  605. [source,java,role="primary"]
  606. ----
  607. @Bean
  608. public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
  609. ReactiveClientRegistrationRepository clientRegistrationRepository,
  610. ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
  611. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  612. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  613. .password()
  614. .refreshToken()
  615. .build();
  616. DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
  617. new DefaultReactiveOAuth2AuthorizedClientManager(
  618. clientRegistrationRepository, authorizedClientRepository);
  619. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  620. // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters,
  621. // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
  622. authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());
  623. return authorizedClientManager;
  624. }
  625. private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper() {
  626. return authorizeRequest -> {
  627. Map<String, Object> contextAttributes = Collections.emptyMap();
  628. ServerWebExchange exchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
  629. ServerHttpRequest request = exchange.getRequest();
  630. String username = request.getQueryParams().getFirst(OAuth2ParameterNames.USERNAME);
  631. String password = request.getQueryParams().getFirst(OAuth2ParameterNames.PASSWORD);
  632. if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
  633. contextAttributes = new HashMap<>();
  634. // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes
  635. contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
  636. contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
  637. }
  638. return Mono.just(contextAttributes);
  639. };
  640. }
  641. ----
  642. Kotlin::
  643. +
  644. [source,kotlin,role="secondary"]
  645. ----
  646. @Bean
  647. fun authorizedClientManager(
  648. clientRegistrationRepository: ReactiveClientRegistrationRepository,
  649. authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
  650. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  651. .password()
  652. .refreshToken()
  653. .build()
  654. val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
  655. clientRegistrationRepository, authorizedClientRepository)
  656. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  657. // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters,
  658. // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
  659. authorizedClientManager.setContextAttributesMapper(contextAttributesMapper())
  660. return authorizedClientManager
  661. }
  662. private fun contextAttributesMapper(): Function<OAuth2AuthorizeRequest, Mono<MutableMap<String, Any>>> {
  663. return Function { authorizeRequest ->
  664. var contextAttributes: MutableMap<String, Any> = mutableMapOf()
  665. val exchange: ServerWebExchange = authorizeRequest.getAttribute(ServerWebExchange::class.java.name)!!
  666. val request: ServerHttpRequest = exchange.request
  667. val username: String? = request.queryParams.getFirst(OAuth2ParameterNames.USERNAME)
  668. val password: String? = request.queryParams.getFirst(OAuth2ParameterNames.PASSWORD)
  669. if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
  670. contextAttributes = hashMapOf()
  671. // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes
  672. contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username!!
  673. contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password!!
  674. }
  675. Mono.just(contextAttributes)
  676. }
  677. }
  678. ----
  679. ======
  680. You may obtain the `OAuth2AccessToken` as follows:
  681. [tabs]
  682. ======
  683. Java::
  684. +
  685. [source,java,role="primary"]
  686. ----
  687. @Controller
  688. public class OAuth2ClientController {
  689. @Autowired
  690. private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
  691. @GetMapping("/")
  692. public Mono<String> index(Authentication authentication, ServerWebExchange exchange) {
  693. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  694. .principal(authentication)
  695. .attribute(ServerWebExchange.class.getName(), exchange)
  696. .build();
  697. return this.authorizedClientManager.authorize(authorizeRequest)
  698. .map(OAuth2AuthorizedClient::getAccessToken)
  699. ...
  700. .thenReturn("index");
  701. }
  702. }
  703. ----
  704. Kotlin::
  705. +
  706. [source,kotlin,role="secondary"]
  707. ----
  708. @Controller
  709. class OAuth2ClientController {
  710. @Autowired
  711. private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager
  712. @GetMapping("/")
  713. fun index(authentication: Authentication, exchange: ServerWebExchange): Mono<String> {
  714. val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  715. .principal(authentication)
  716. .attribute(ServerWebExchange::class.java.name, exchange)
  717. .build()
  718. return authorizedClientManager.authorize(authorizeRequest)
  719. .map { it.accessToken }
  720. ...
  721. .thenReturn("index")
  722. }
  723. }
  724. ----
  725. ======
  726. [NOTE]
  727. `ServerWebExchange` is an OPTIONAL attribute.
  728. If not provided, it will be obtained from the https://projectreactor.io/docs/core/release/reference/#context[Reactor's Context] via the key `ServerWebExchange.class`.
  729. [[oauth2Client-jwt-bearer-grant]]
  730. == JWT Bearer
  731. [NOTE]
  732. Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on the https://datatracker.ietf.org/doc/html/rfc7523[JWT Bearer] grant.
  733. === Requesting an Access Token
  734. [NOTE]
  735. Please refer to the https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[Access Token Request/Response] protocol flow for the JWT Bearer grant.
  736. The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the JWT Bearer grant is `WebClientReactiveJwtBearerTokenResponseClient`, which uses a `WebClient` when requesting an access token at the Authorization Server’s Token Endpoint.
  737. The `WebClientReactiveJwtBearerTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.
  738. === Customizing the Access Token Request
  739. If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveJwtBearerTokenResponseClient.setParametersConverter()` with a custom `Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>`.
  740. The default implementation builds a `MultiValueMap<String, String>` containing only the `grant_type` parameter of a standard https://tools.ietf.org/html/rfc6749#section-4.4.2[OAuth 2.0 Access Token Request] which is used to construct the request. Other parameters required by the JWT Bearer grant are added directly to the body of the request by the `WebClientReactiveJwtBearerTokenResponseClient`.
  741. However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s).
  742. [TIP]
  743. If you prefer to only add additional parameters, you can instead provide `WebClientReactiveJwtBearerTokenResponseClient.addParametersConverter()` with a custom `Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>` which constructs an aggregate `Converter`.
  744. IMPORTANT: The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.
  745. === Customizing the Access Token Response
  746. On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveJwtBearerTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`.
  747. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly.
  748. === Customizing the `WebClient`
  749. Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveJwtBearerTokenResponseClient.setWebClient()` with a custom configured `WebClient`.
  750. Whether you customize `WebClientReactiveJwtBearerTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example:
  751. [tabs]
  752. ======
  753. Java::
  754. +
  755. [source,java,role="primary"]
  756. ----
  757. // Customize
  758. ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient = ...
  759. JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerReactiveOAuth2AuthorizedClientProvider();
  760. jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);
  761. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  762. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  763. .provider(jwtBearerAuthorizedClientProvider)
  764. .build();
  765. ...
  766. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  767. ----
  768. Kotlin::
  769. +
  770. [source,kotlin,role="secondary"]
  771. ----
  772. // Customize
  773. val jwtBearerTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> = ...
  774. val jwtBearerAuthorizedClientProvider = JwtBearerReactiveOAuth2AuthorizedClientProvider()
  775. jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient)
  776. val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  777. .provider(jwtBearerAuthorizedClientProvider)
  778. .build()
  779. ...
  780. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  781. ----
  782. ======
  783. === Using the Access Token
  784. Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:
  785. [source,yaml]
  786. ----
  787. spring:
  788. security:
  789. oauth2:
  790. client:
  791. registration:
  792. okta:
  793. client-id: okta-client-id
  794. client-secret: okta-client-secret
  795. authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer
  796. scope: read
  797. provider:
  798. okta:
  799. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  800. ----
  801. ...and the `OAuth2AuthorizedClientManager` `@Bean`:
  802. [tabs]
  803. ======
  804. Java::
  805. +
  806. [source,java,role="primary"]
  807. ----
  808. @Bean
  809. public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
  810. ReactiveClientRegistrationRepository clientRegistrationRepository,
  811. ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
  812. JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider =
  813. new JwtBearerReactiveOAuth2AuthorizedClientProvider();
  814. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  815. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  816. .provider(jwtBearerAuthorizedClientProvider)
  817. .build();
  818. DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
  819. new DefaultReactiveOAuth2AuthorizedClientManager(
  820. clientRegistrationRepository, authorizedClientRepository);
  821. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  822. return authorizedClientManager;
  823. }
  824. ----
  825. Kotlin::
  826. +
  827. [source,kotlin,role="secondary"]
  828. ----
  829. @Bean
  830. fun authorizedClientManager(
  831. clientRegistrationRepository: ReactiveClientRegistrationRepository,
  832. authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
  833. val jwtBearerAuthorizedClientProvider = JwtBearerReactiveOAuth2AuthorizedClientProvider()
  834. val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  835. .provider(jwtBearerAuthorizedClientProvider)
  836. .build()
  837. val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
  838. clientRegistrationRepository, authorizedClientRepository)
  839. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  840. return authorizedClientManager
  841. }
  842. ----
  843. ======
  844. You may obtain the `OAuth2AccessToken` as follows:
  845. [tabs]
  846. ======
  847. Java::
  848. +
  849. [source,java,role="primary"]
  850. ----
  851. @RestController
  852. public class OAuth2ResourceServerController {
  853. @Autowired
  854. private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
  855. @GetMapping("/resource")
  856. public Mono<String> resource(JwtAuthenticationToken jwtAuthentication, ServerWebExchange exchange) {
  857. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  858. .principal(jwtAuthentication)
  859. .build();
  860. return this.authorizedClientManager.authorize(authorizeRequest)
  861. .map(OAuth2AuthorizedClient::getAccessToken)
  862. ...
  863. }
  864. }
  865. ----
  866. Kotlin::
  867. +
  868. [source,kotlin,role="secondary"]
  869. ----
  870. class OAuth2ResourceServerController {
  871. @Autowired
  872. private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager
  873. @GetMapping("/resource")
  874. fun resource(jwtAuthentication: JwtAuthenticationToken, exchange: ServerWebExchange): Mono<String> {
  875. val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  876. .principal(jwtAuthentication)
  877. .build()
  878. return authorizedClientManager.authorize(authorizeRequest)
  879. .map { it.accessToken }
  880. ...
  881. }
  882. }
  883. ----
  884. ======
  885. [NOTE]
  886. `JwtBearerReactiveOAuth2AuthorizedClientProvider` resolves the `Jwt` assertion via `OAuth2AuthorizationContext.getPrincipal().getPrincipal()` by default, hence the use of `JwtAuthenticationToken` in the preceding example.
  887. [TIP]
  888. If you need to resolve the `Jwt` assertion from a different source, you can provide `JwtBearerReactiveOAuth2AuthorizedClientProvider.setJwtAssertionResolver()` with a custom `Function<OAuth2AuthorizationContext, Mono<Jwt>>`.