2
0

authorization-grants.adoc 47 KB

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