authorization-grants.adoc 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. @Configuration
  91. @EnableWebFluxSecurity
  92. public class OAuth2LoginSecurityConfig {
  93. @Autowired
  94. private ReactiveClientRegistrationRepository clientRegistrationRepository;
  95. @Bean
  96. public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
  97. http
  98. .authorizeExchange(authorize -> authorize
  99. .anyExchange().authenticated()
  100. )
  101. .oauth2Login(oauth2 -> oauth2
  102. .authorizationRequestResolver(
  103. authorizationRequestResolver(this.clientRegistrationRepository)
  104. )
  105. );
  106. return http.build();
  107. }
  108. private ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver(
  109. ReactiveClientRegistrationRepository clientRegistrationRepository) {
  110. DefaultServerOAuth2AuthorizationRequestResolver authorizationRequestResolver =
  111. new DefaultServerOAuth2AuthorizationRequestResolver(
  112. clientRegistrationRepository);
  113. authorizationRequestResolver.setAuthorizationRequestCustomizer(
  114. authorizationRequestCustomizer());
  115. return authorizationRequestResolver;
  116. }
  117. private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
  118. return customizer -> customizer
  119. .additionalParameters(params -> params.put("prompt", "consent"));
  120. }
  121. }
  122. ----
  123. Kotlin::
  124. +
  125. [source,kotlin,role="secondary"]
  126. ----
  127. @Configuration
  128. @EnableWebFluxSecurity
  129. class SecurityConfig {
  130. @Autowired
  131. private lateinit var customClientRegistrationRepository: ReactiveClientRegistrationRepository
  132. @Bean
  133. fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  134. http {
  135. authorizeExchange {
  136. authorize(anyExchange, authenticated)
  137. }
  138. oauth2Login {
  139. authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
  140. }
  141. }
  142. return http.build()
  143. }
  144. private fun authorizationRequestResolver(
  145. clientRegistrationRepository: ReactiveClientRegistrationRepository): ServerOAuth2AuthorizationRequestResolver {
  146. val authorizationRequestResolver = DefaultServerOAuth2AuthorizationRequestResolver(
  147. clientRegistrationRepository)
  148. authorizationRequestResolver.setAuthorizationRequestCustomizer(
  149. authorizationRequestCustomizer())
  150. return authorizationRequestResolver
  151. }
  152. private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
  153. return Consumer { customizer ->
  154. customizer
  155. .additionalParameters { params -> params["prompt"] = "consent" }
  156. }
  157. }
  158. }
  159. ----
  160. ======
  161. 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.
  162. For example, if the value for the request parameter `prompt` is always `consent` for the provider `okta`, than simply configure as follows:
  163. [source,yaml]
  164. ----
  165. spring:
  166. security:
  167. oauth2:
  168. client:
  169. provider:
  170. okta:
  171. authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent
  172. ----
  173. The preceding example shows the common use case of adding a custom parameter on top of the standard parameters.
  174. 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.
  175. [TIP]
  176. `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.
  177. The following example shows a variation of `authorizationRequestCustomizer()` from the preceding example, and instead overrides the `OAuth2AuthorizationRequest.authorizationRequestUri` property.
  178. [tabs]
  179. ======
  180. Java::
  181. +
  182. [source,java,role="primary"]
  183. ----
  184. private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
  185. return customizer -> customizer
  186. .authorizationRequestUri(uriBuilder -> uriBuilder
  187. .queryParam("prompt", "consent").build());
  188. }
  189. ----
  190. Kotlin::
  191. +
  192. [source,kotlin,role="secondary"]
  193. ----
  194. private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
  195. return Consumer { customizer: OAuth2AuthorizationRequest.Builder ->
  196. customizer
  197. .authorizationRequestUri { uriBuilder: UriBuilder ->
  198. uriBuilder
  199. .queryParam("prompt", "consent").build()
  200. }
  201. }
  202. }
  203. ----
  204. ======
  205. === Storing the Authorization Request
  206. 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).
  207. [TIP]
  208. The `OAuth2AuthorizationRequest` is used to correlate and validate the Authorization Response.
  209. The default implementation of `ServerAuthorizationRequestRepository` is `WebSessionOAuth2ServerAuthorizationRequestRepository`, which stores the `OAuth2AuthorizationRequest` in the `WebSession`.
  210. If you have a custom implementation of `ServerAuthorizationRequestRepository`, you may configure it as shown in the following example:
  211. .ServerAuthorizationRequestRepository Configuration
  212. [tabs]
  213. ======
  214. Java::
  215. +
  216. [source,java,role="primary"]
  217. ----
  218. @Configuration
  219. @EnableWebFluxSecurity
  220. public class OAuth2ClientSecurityConfig {
  221. @Bean
  222. public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
  223. http
  224. .oauth2Client(oauth2 -> oauth2
  225. .authorizationRequestRepository(this.authorizationRequestRepository())
  226. ...
  227. );
  228. return http.build();
  229. }
  230. }
  231. ----
  232. Kotlin::
  233. +
  234. [source,kotlin,role="secondary"]
  235. ----
  236. @Configuration
  237. @EnableWebFluxSecurity
  238. class OAuth2ClientSecurityConfig {
  239. @Bean
  240. fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  241. http {
  242. oauth2Client {
  243. authorizationRequestRepository = authorizationRequestRepository()
  244. }
  245. }
  246. return http.build()
  247. }
  248. }
  249. ----
  250. ======
  251. === Requesting an Access Token
  252. [NOTE]
  253. 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.
  254. 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.
  255. 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.
  256. === Customizing the Access Token Request
  257. 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>>`.
  258. 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`.
  259. However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s).
  260. [TIP]
  261. 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`.
  262. 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.
  263. === Customizing the Access Token Response
  264. 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`.
  265. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly.
  266. === Customizing the `WebClient`
  267. 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`.
  268. Whether you customize `WebClientReactiveAuthorizationCodeTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example:
  269. .Access Token Response Configuration
  270. [tabs]
  271. ======
  272. Java::
  273. +
  274. [source,java,role="primary"]
  275. ----
  276. @Configuration
  277. @EnableWebFluxSecurity
  278. public class OAuth2ClientSecurityConfig {
  279. @Bean
  280. public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
  281. http
  282. .oauth2Client(oauth2 -> oauth2
  283. .authenticationManager(this.authorizationCodeAuthenticationManager())
  284. ...
  285. );
  286. return http.build();
  287. }
  288. private ReactiveAuthenticationManager authorizationCodeAuthenticationManager() {
  289. WebClientReactiveAuthorizationCodeTokenResponseClient accessTokenResponseClient =
  290. new WebClientReactiveAuthorizationCodeTokenResponseClient();
  291. ...
  292. return new OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient);
  293. }
  294. }
  295. ----
  296. Kotlin::
  297. +
  298. [source,kotlin,role="secondary"]
  299. ----
  300. @Configuration
  301. @EnableWebFluxSecurity
  302. class OAuth2ClientSecurityConfig {
  303. @Bean
  304. fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  305. http {
  306. oauth2Client {
  307. authenticationManager = authorizationCodeAuthenticationManager()
  308. }
  309. }
  310. return http.build()
  311. }
  312. private fun authorizationCodeAuthenticationManager(): ReactiveAuthenticationManager {
  313. val accessTokenResponseClient = WebClientReactiveAuthorizationCodeTokenResponseClient()
  314. ...
  315. return OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient)
  316. }
  317. }
  318. ----
  319. ======
  320. [[oauth2Client-refresh-token-grant]]
  321. == Refresh Token
  322. [NOTE]
  323. 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].
  324. === Refreshing an Access Token
  325. [NOTE]
  326. Please refer to the https://tools.ietf.org/html/rfc6749#section-6[Access Token Request/Response] protocol flow for the Refresh Token grant.
  327. 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.
  328. 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.
  329. === Customizing the Access Token Request
  330. 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>>`.
  331. 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`.
  332. However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s).
  333. [TIP]
  334. 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`.
  335. 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.
  336. === Customizing the Access Token Response
  337. 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`.
  338. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly.
  339. === Customizing the `WebClient`
  340. 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`.
  341. Whether you customize `WebClientReactiveRefreshTokenTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example:
  342. .Access Token Response Configuration
  343. [tabs]
  344. ======
  345. Java::
  346. +
  347. [source,java,role="primary"]
  348. ----
  349. // Customize
  350. ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient = ...
  351. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  352. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  353. .authorizationCode()
  354. .refreshToken(configurer -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
  355. .build();
  356. ...
  357. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  358. ----
  359. Kotlin::
  360. +
  361. [source,kotlin,role="secondary"]
  362. ----
  363. // Customize
  364. val refreshTokenTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> = ...
  365. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  366. .authorizationCode()
  367. .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
  368. .build()
  369. ...
  370. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  371. ----
  372. ======
  373. [NOTE]
  374. `ReactiveOAuth2AuthorizedClientProviderBuilder.builder().refreshToken()` configures a `RefreshTokenReactiveOAuth2AuthorizedClientProvider`,
  375. which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Refresh Token grant.
  376. The `OAuth2RefreshToken` may optionally be returned in the Access Token Response for the `authorization_code` and `password` grant types.
  377. If the `OAuth2AuthorizedClient.getRefreshToken()` is available and the `OAuth2AuthorizedClient.getAccessToken()` is expired, it will automatically be refreshed by the `RefreshTokenReactiveOAuth2AuthorizedClientProvider`.
  378. [[oauth2Client-client-creds-grant]]
  379. == Client Credentials
  380. [NOTE]
  381. 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.
  382. === Requesting an Access Token
  383. [NOTE]
  384. 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.
  385. 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.
  386. 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.
  387. === Customizing the Access Token Request
  388. 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>>`.
  389. 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`.
  390. However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s).
  391. [TIP]
  392. 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`.
  393. 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.
  394. === Customizing the Access Token Response
  395. 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`.
  396. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly.
  397. === Customizing the `WebClient`
  398. 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`.
  399. Whether you customize `WebClientReactiveClientCredentialsTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example:
  400. [tabs]
  401. ======
  402. Java::
  403. +
  404. [source,java,role="primary"]
  405. ----
  406. // Customize
  407. ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = ...
  408. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  409. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  410. .clientCredentials(configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
  411. .build();
  412. ...
  413. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  414. ----
  415. Kotlin::
  416. +
  417. [source,kotlin,role="secondary"]
  418. ----
  419. // Customize
  420. val clientCredentialsTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> = ...
  421. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  422. .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
  423. .build()
  424. ...
  425. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  426. ----
  427. ======
  428. [NOTE]
  429. `ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsReactiveOAuth2AuthorizedClientProvider`,
  430. which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Client Credentials grant.
  431. === Using the Access Token
  432. Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:
  433. [source,yaml]
  434. ----
  435. spring:
  436. security:
  437. oauth2:
  438. client:
  439. registration:
  440. okta:
  441. client-id: okta-client-id
  442. client-secret: okta-client-secret
  443. authorization-grant-type: client_credentials
  444. scope: read, write
  445. provider:
  446. okta:
  447. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  448. ----
  449. ...and the `ReactiveOAuth2AuthorizedClientManager` `@Bean`:
  450. [tabs]
  451. ======
  452. Java::
  453. +
  454. [source,java,role="primary"]
  455. ----
  456. @Bean
  457. public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
  458. ReactiveClientRegistrationRepository clientRegistrationRepository,
  459. ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
  460. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  461. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  462. .clientCredentials()
  463. .build();
  464. DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
  465. new DefaultReactiveOAuth2AuthorizedClientManager(
  466. clientRegistrationRepository, authorizedClientRepository);
  467. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  468. return authorizedClientManager;
  469. }
  470. ----
  471. Kotlin::
  472. +
  473. [source,kotlin,role="secondary"]
  474. ----
  475. @Bean
  476. fun authorizedClientManager(
  477. clientRegistrationRepository: ReactiveClientRegistrationRepository,
  478. authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
  479. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  480. .clientCredentials()
  481. .build()
  482. val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
  483. clientRegistrationRepository, authorizedClientRepository)
  484. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  485. return authorizedClientManager
  486. }
  487. ----
  488. ======
  489. You may obtain the `OAuth2AccessToken` as follows:
  490. [tabs]
  491. ======
  492. Java::
  493. +
  494. [source,java,role="primary"]
  495. ----
  496. @Controller
  497. public class OAuth2ClientController {
  498. @Autowired
  499. private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
  500. @GetMapping("/")
  501. public Mono<String> index(Authentication authentication, ServerWebExchange exchange) {
  502. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  503. .principal(authentication)
  504. .attribute(ServerWebExchange.class.getName(), exchange)
  505. .build();
  506. return this.authorizedClientManager.authorize(authorizeRequest)
  507. .map(OAuth2AuthorizedClient::getAccessToken)
  508. ...
  509. .thenReturn("index");
  510. }
  511. }
  512. ----
  513. Kotlin::
  514. +
  515. [source,kotlin,role="secondary"]
  516. ----
  517. class OAuth2ClientController {
  518. @Autowired
  519. private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager
  520. @GetMapping("/")
  521. fun index(authentication: Authentication, exchange: ServerWebExchange): Mono<String> {
  522. val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  523. .principal(authentication)
  524. .attribute(ServerWebExchange::class.java.name, exchange)
  525. .build()
  526. return authorizedClientManager.authorize(authorizeRequest)
  527. .map { it.accessToken }
  528. ...
  529. .thenReturn("index")
  530. }
  531. }
  532. ----
  533. ======
  534. [NOTE]
  535. `ServerWebExchange` is an OPTIONAL attribute.
  536. 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`.
  537. [[oauth2Client-password-grant]]
  538. == Resource Owner Password Credentials
  539. [NOTE]
  540. 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.
  541. === Requesting an Access Token
  542. [NOTE]
  543. 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.
  544. 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.
  545. 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.
  546. === Customizing the Access Token Request
  547. 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>>`.
  548. 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`.
  549. However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s).
  550. [TIP]
  551. 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`.
  552. 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.
  553. === Customizing the Access Token Response
  554. 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`.
  555. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly.
  556. === Customizing the `WebClient`
  557. 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`.
  558. Whether you customize `WebClientReactivePasswordTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example:
  559. [tabs]
  560. ======
  561. Java::
  562. +
  563. [source,java,role="primary"]
  564. ----
  565. // Customize
  566. ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient = ...
  567. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  568. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  569. .password(configurer -> configurer.accessTokenResponseClient(passwordTokenResponseClient))
  570. .refreshToken()
  571. .build();
  572. ...
  573. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  574. ----
  575. Kotlin::
  576. +
  577. [source,kotlin,role="secondary"]
  578. ----
  579. val passwordTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...
  580. val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  581. .password { it.accessTokenResponseClient(passwordTokenResponseClient) }
  582. .refreshToken()
  583. .build()
  584. ...
  585. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  586. ----
  587. ======
  588. [NOTE]
  589. `ReactiveOAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordReactiveOAuth2AuthorizedClientProvider`,
  590. which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Resource Owner Password Credentials grant.
  591. === Using the Access Token
  592. Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:
  593. [source,yaml]
  594. ----
  595. spring:
  596. security:
  597. oauth2:
  598. client:
  599. registration:
  600. okta:
  601. client-id: okta-client-id
  602. client-secret: okta-client-secret
  603. authorization-grant-type: password
  604. scope: read, write
  605. provider:
  606. okta:
  607. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  608. ----
  609. ...and the `ReactiveOAuth2AuthorizedClientManager` `@Bean`:
  610. [tabs]
  611. ======
  612. Java::
  613. +
  614. [source,java,role="primary"]
  615. ----
  616. @Bean
  617. public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
  618. ReactiveClientRegistrationRepository clientRegistrationRepository,
  619. ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
  620. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  621. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  622. .password()
  623. .refreshToken()
  624. .build();
  625. DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
  626. new DefaultReactiveOAuth2AuthorizedClientManager(
  627. clientRegistrationRepository, authorizedClientRepository);
  628. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  629. // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters,
  630. // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
  631. authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());
  632. return authorizedClientManager;
  633. }
  634. private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper() {
  635. return authorizeRequest -> {
  636. Map<String, Object> contextAttributes = Collections.emptyMap();
  637. ServerWebExchange exchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
  638. ServerHttpRequest request = exchange.getRequest();
  639. String username = request.getQueryParams().getFirst(OAuth2ParameterNames.USERNAME);
  640. String password = request.getQueryParams().getFirst(OAuth2ParameterNames.PASSWORD);
  641. if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
  642. contextAttributes = new HashMap<>();
  643. // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes
  644. contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
  645. contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
  646. }
  647. return Mono.just(contextAttributes);
  648. };
  649. }
  650. ----
  651. Kotlin::
  652. +
  653. [source,kotlin,role="secondary"]
  654. ----
  655. @Bean
  656. fun authorizedClientManager(
  657. clientRegistrationRepository: ReactiveClientRegistrationRepository,
  658. authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
  659. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  660. .password()
  661. .refreshToken()
  662. .build()
  663. val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
  664. clientRegistrationRepository, authorizedClientRepository)
  665. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  666. // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters,
  667. // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
  668. authorizedClientManager.setContextAttributesMapper(contextAttributesMapper())
  669. return authorizedClientManager
  670. }
  671. private fun contextAttributesMapper(): Function<OAuth2AuthorizeRequest, Mono<MutableMap<String, Any>>> {
  672. return Function { authorizeRequest ->
  673. var contextAttributes: MutableMap<String, Any> = mutableMapOf()
  674. val exchange: ServerWebExchange = authorizeRequest.getAttribute(ServerWebExchange::class.java.name)!!
  675. val request: ServerHttpRequest = exchange.request
  676. val username: String? = request.queryParams.getFirst(OAuth2ParameterNames.USERNAME)
  677. val password: String? = request.queryParams.getFirst(OAuth2ParameterNames.PASSWORD)
  678. if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
  679. contextAttributes = hashMapOf()
  680. // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes
  681. contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username!!
  682. contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password!!
  683. }
  684. Mono.just(contextAttributes)
  685. }
  686. }
  687. ----
  688. ======
  689. You may obtain the `OAuth2AccessToken` as follows:
  690. [tabs]
  691. ======
  692. Java::
  693. +
  694. [source,java,role="primary"]
  695. ----
  696. @Controller
  697. public class OAuth2ClientController {
  698. @Autowired
  699. private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
  700. @GetMapping("/")
  701. public Mono<String> index(Authentication authentication, ServerWebExchange exchange) {
  702. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  703. .principal(authentication)
  704. .attribute(ServerWebExchange.class.getName(), exchange)
  705. .build();
  706. return this.authorizedClientManager.authorize(authorizeRequest)
  707. .map(OAuth2AuthorizedClient::getAccessToken)
  708. ...
  709. .thenReturn("index");
  710. }
  711. }
  712. ----
  713. Kotlin::
  714. +
  715. [source,kotlin,role="secondary"]
  716. ----
  717. @Controller
  718. class OAuth2ClientController {
  719. @Autowired
  720. private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager
  721. @GetMapping("/")
  722. fun index(authentication: Authentication, exchange: ServerWebExchange): Mono<String> {
  723. val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  724. .principal(authentication)
  725. .attribute(ServerWebExchange::class.java.name, exchange)
  726. .build()
  727. return authorizedClientManager.authorize(authorizeRequest)
  728. .map { it.accessToken }
  729. ...
  730. .thenReturn("index")
  731. }
  732. }
  733. ----
  734. ======
  735. [NOTE]
  736. `ServerWebExchange` is an OPTIONAL attribute.
  737. 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`.
  738. [[oauth2Client-jwt-bearer-grant]]
  739. == JWT Bearer
  740. [NOTE]
  741. 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.
  742. === Requesting an Access Token
  743. [NOTE]
  744. 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.
  745. 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.
  746. 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.
  747. === Customizing the Access Token Request
  748. 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>>`.
  749. 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`.
  750. However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s).
  751. [TIP]
  752. 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`.
  753. 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.
  754. === Customizing the Access Token Response
  755. 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`.
  756. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly.
  757. === Customizing the `WebClient`
  758. 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`.
  759. Whether you customize `WebClientReactiveJwtBearerTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example:
  760. [tabs]
  761. ======
  762. Java::
  763. +
  764. [source,java,role="primary"]
  765. ----
  766. // Customize
  767. ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient = ...
  768. JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerReactiveOAuth2AuthorizedClientProvider();
  769. jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);
  770. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  771. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  772. .provider(jwtBearerAuthorizedClientProvider)
  773. .build();
  774. ...
  775. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  776. ----
  777. Kotlin::
  778. +
  779. [source,kotlin,role="secondary"]
  780. ----
  781. // Customize
  782. val jwtBearerTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> = ...
  783. val jwtBearerAuthorizedClientProvider = JwtBearerReactiveOAuth2AuthorizedClientProvider()
  784. jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient)
  785. val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  786. .provider(jwtBearerAuthorizedClientProvider)
  787. .build()
  788. ...
  789. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  790. ----
  791. ======
  792. === Using the Access Token
  793. Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration:
  794. [source,yaml]
  795. ----
  796. spring:
  797. security:
  798. oauth2:
  799. client:
  800. registration:
  801. okta:
  802. client-id: okta-client-id
  803. client-secret: okta-client-secret
  804. authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer
  805. scope: read
  806. provider:
  807. okta:
  808. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  809. ----
  810. ...and the `OAuth2AuthorizedClientManager` `@Bean`:
  811. [tabs]
  812. ======
  813. Java::
  814. +
  815. [source,java,role="primary"]
  816. ----
  817. @Bean
  818. public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
  819. ReactiveClientRegistrationRepository clientRegistrationRepository,
  820. ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
  821. JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider =
  822. new JwtBearerReactiveOAuth2AuthorizedClientProvider();
  823. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  824. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  825. .provider(jwtBearerAuthorizedClientProvider)
  826. .build();
  827. DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
  828. new DefaultReactiveOAuth2AuthorizedClientManager(
  829. clientRegistrationRepository, authorizedClientRepository);
  830. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  831. return authorizedClientManager;
  832. }
  833. ----
  834. Kotlin::
  835. +
  836. [source,kotlin,role="secondary"]
  837. ----
  838. @Bean
  839. fun authorizedClientManager(
  840. clientRegistrationRepository: ReactiveClientRegistrationRepository,
  841. authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
  842. val jwtBearerAuthorizedClientProvider = JwtBearerReactiveOAuth2AuthorizedClientProvider()
  843. val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  844. .provider(jwtBearerAuthorizedClientProvider)
  845. .build()
  846. val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
  847. clientRegistrationRepository, authorizedClientRepository)
  848. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  849. return authorizedClientManager
  850. }
  851. ----
  852. ======
  853. You may obtain the `OAuth2AccessToken` as follows:
  854. [tabs]
  855. ======
  856. Java::
  857. +
  858. [source,java,role="primary"]
  859. ----
  860. @RestController
  861. public class OAuth2ResourceServerController {
  862. @Autowired
  863. private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
  864. @GetMapping("/resource")
  865. public Mono<String> resource(JwtAuthenticationToken jwtAuthentication, ServerWebExchange exchange) {
  866. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  867. .principal(jwtAuthentication)
  868. .build();
  869. return this.authorizedClientManager.authorize(authorizeRequest)
  870. .map(OAuth2AuthorizedClient::getAccessToken)
  871. ...
  872. }
  873. }
  874. ----
  875. Kotlin::
  876. +
  877. [source,kotlin,role="secondary"]
  878. ----
  879. class OAuth2ResourceServerController {
  880. @Autowired
  881. private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager
  882. @GetMapping("/resource")
  883. fun resource(jwtAuthentication: JwtAuthenticationToken, exchange: ServerWebExchange): Mono<String> {
  884. val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  885. .principal(jwtAuthentication)
  886. .build()
  887. return authorizedClientManager.authorize(authorizeRequest)
  888. .map { it.accessToken }
  889. ...
  890. }
  891. }
  892. ----
  893. ======
  894. [NOTE]
  895. `JwtBearerReactiveOAuth2AuthorizedClientProvider` resolves the `Jwt` assertion via `OAuth2AuthorizationContext.getPrincipal().getPrincipal()` by default, hence the use of `JwtAuthenticationToken` in the preceding example.
  896. [TIP]
  897. If you need to resolve the `Jwt` assertion from a different source, you can provide `JwtBearerReactiveOAuth2AuthorizedClientProvider.setJwtAssertionResolver()` with a custom `Function<OAuth2AuthorizationContext, Mono<Jwt>>`.