authorization-grants.adoc 47 KB

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