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