authorization-grants.adoc 47 KB

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