authorization-grants.adoc 47 KB

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