authorization-grants.adoc 47 KB

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