authorization-grants.adoc 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  1. [[oauth2-client-authorization-grants]]
  2. = [[oauth2Client-auth-grant-support]]Authorization Grant Support
  3. This section describes Spring Security's support for authorization grants.
  4. [[oauth2-client-authorization-code]]
  5. == [[oauth2Client-auth-code-grant]]Authorization Code
  6. [NOTE]
  7. ====
  8. 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.
  9. ====
  10. [[oauth2-client-authorization-code-authorization]]
  11. === Obtaining Authorization
  12. [NOTE]
  13. ====
  14. Please refer to the https://tools.ietf.org/html/rfc6749#section-4.1.1[Authorization Request/Response] protocol flow for the Authorization Code grant.
  15. ====
  16. [[oauth2-client-authorization-code-authorization-request]]
  17. === Initiating the Authorization Request
  18. 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.
  19. The primary role of the `ServerOAuth2AuthorizationRequestResolver` is to resolve an `OAuth2AuthorizationRequest` from the provided web request.
  20. 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`.
  21. Given the following Spring Boot properties for an OAuth 2.0 Client registration:
  22. [source,yaml,attrs="-attributes"]
  23. ----
  24. spring:
  25. security:
  26. oauth2:
  27. client:
  28. registration:
  29. okta:
  30. client-id: okta-client-id
  31. client-secret: okta-client-secret
  32. authorization-grant-type: authorization_code
  33. redirect-uri: "{baseUrl}/authorized/okta"
  34. scope: read, write
  35. provider:
  36. okta:
  37. authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize
  38. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  39. ----
  40. 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.
  41. [NOTE]
  42. ====
  43. The `AuthorizationCodeReactiveOAuth2AuthorizedClientProvider` is an implementation of `ReactiveOAuth2AuthorizedClientProvider` for the Authorization Code grant,
  44. which also initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectWebFilter`.
  45. ====
  46. 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:
  47. [source,yaml,attrs="-attributes"]
  48. ----
  49. spring:
  50. security:
  51. oauth2:
  52. client:
  53. registration:
  54. okta:
  55. client-id: okta-client-id
  56. client-authentication-method: none
  57. authorization-grant-type: authorization_code
  58. redirect-uri: "{baseUrl}/authorized/okta"
  59. # ...
  60. ----
  61. Public Clients are supported using https://tools.ietf.org/html/rfc7636[Proof Key for Code Exchange] (PKCE).
  62. 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:
  63. . `client-secret` is omitted (or empty)
  64. . `client-authentication-method` is set to "none" (`ClientAuthenticationMethod.NONE`)
  65. or
  66. . When `ClientRegistration.clientSettings.requireProofKey` is `true` (in this case `ClientRegistration.authorizationGrantType` must be `authorization_code`)
  67. [TIP]
  68. ====
  69. If the OAuth 2.0 Provider supports PKCE for https://tools.ietf.org/html/rfc6749#section-2.1[Confidential Clients], you may (optionally) configure it using `DefaultServerOAuth2AuthorizationRequestResolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce())`.
  70. ====
  71. [[oauth2-client-authorization-code-redirect-uri]]
  72. [[oauth2Client-auth-code-redirect-uri]]The `DefaultServerOAuth2AuthorizationRequestResolver` also supports `URI` template variables for the `redirect-uri` using `UriComponentsBuilder`.
  73. The following configuration uses all the supported `URI` template variables:
  74. [source,yaml,attrs="-attributes"]
  75. ----
  76. spring:
  77. security:
  78. oauth2:
  79. client:
  80. registration:
  81. okta:
  82. # ...
  83. redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}"
  84. # ...
  85. ----
  86. [NOTE]
  87. ====
  88. `+{baseUrl}+` resolves to `+{baseScheme}://{baseHost}{basePort}{basePath}+`
  89. ====
  90. 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].
  91. This ensures that the `X-Forwarded-*` headers are used when expanding the `redirect-uri`.
  92. [[oauth2-client-authorization-code-authorization-request-resolver]]
  93. === Customizing the Authorization Request
  94. 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.
  95. 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].
  96. One of those extended parameters is the `prompt` parameter.
  97. [NOTE]
  98. ====
  99. The `prompt` parameter is optional. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for re-authentication and consent. The defined values are: `none`, `login`, `consent`, and `select_account`.
  100. ====
  101. 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`.
  102. [tabs]
  103. ======
  104. Java::
  105. +
  106. [source,java,role="primary"]
  107. ----
  108. @Configuration
  109. @EnableWebFluxSecurity
  110. public class OAuth2LoginSecurityConfig {
  111. @Autowired
  112. private ReactiveClientRegistrationRepository clientRegistrationRepository;
  113. @Bean
  114. public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
  115. http
  116. .authorizeExchange((authorize) -> authorize
  117. .anyExchange().authenticated()
  118. )
  119. .oauth2Login((oauth2) -> oauth2
  120. .authorizationRequestResolver(
  121. authorizationRequestResolver(this.clientRegistrationRepository)
  122. )
  123. );
  124. return http.build();
  125. }
  126. private ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver(
  127. ReactiveClientRegistrationRepository clientRegistrationRepository) {
  128. DefaultServerOAuth2AuthorizationRequestResolver authorizationRequestResolver =
  129. new DefaultServerOAuth2AuthorizationRequestResolver(
  130. clientRegistrationRepository);
  131. authorizationRequestResolver.setAuthorizationRequestCustomizer(
  132. authorizationRequestCustomizer());
  133. return authorizationRequestResolver;
  134. }
  135. private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
  136. return customizer -> customizer
  137. .additionalParameters((params) -> params.put("prompt", "consent"));
  138. }
  139. }
  140. ----
  141. Kotlin::
  142. +
  143. [source,kotlin,role="secondary"]
  144. ----
  145. @Configuration
  146. @EnableWebFluxSecurity
  147. class SecurityConfig {
  148. @Autowired
  149. private lateinit var customClientRegistrationRepository: ReactiveClientRegistrationRepository
  150. @Bean
  151. fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  152. http {
  153. authorizeExchange {
  154. authorize(anyExchange, authenticated)
  155. }
  156. oauth2Login {
  157. authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
  158. }
  159. }
  160. return http.build()
  161. }
  162. private fun authorizationRequestResolver(
  163. clientRegistrationRepository: ReactiveClientRegistrationRepository): ServerOAuth2AuthorizationRequestResolver {
  164. val authorizationRequestResolver = DefaultServerOAuth2AuthorizationRequestResolver(
  165. clientRegistrationRepository)
  166. authorizationRequestResolver.setAuthorizationRequestCustomizer(
  167. authorizationRequestCustomizer())
  168. return authorizationRequestResolver
  169. }
  170. private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
  171. return Consumer { customizer ->
  172. customizer
  173. .additionalParameters { params -> params["prompt"] = "consent" }
  174. }
  175. }
  176. }
  177. ----
  178. ======
  179. 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.
  180. For example, if the value for the request parameter `prompt` is always `consent` for the provider `okta`, than simply configure as follows:
  181. [source,yaml]
  182. ----
  183. spring:
  184. security:
  185. oauth2:
  186. client:
  187. provider:
  188. okta:
  189. authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent
  190. ----
  191. The preceding example shows the common use case of adding a custom parameter on top of the standard parameters.
  192. 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.
  193. [TIP]
  194. ====
  195. `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.
  196. ====
  197. The following example shows a variation of `authorizationRequestCustomizer()` from the preceding example, and instead overrides the `OAuth2AuthorizationRequest.authorizationRequestUri` property.
  198. [tabs]
  199. ======
  200. Java::
  201. +
  202. [source,java,role="primary"]
  203. ----
  204. private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
  205. return customizer -> customizer
  206. .authorizationRequestUri((uriBuilder) -> uriBuilder
  207. .queryParam("prompt", "consent").build());
  208. }
  209. ----
  210. Kotlin::
  211. +
  212. [source,kotlin,role="secondary"]
  213. ----
  214. private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
  215. return Consumer { customizer: OAuth2AuthorizationRequest.Builder ->
  216. customizer
  217. .authorizationRequestUri { uriBuilder: UriBuilder ->
  218. uriBuilder
  219. .queryParam("prompt", "consent").build()
  220. }
  221. }
  222. }
  223. ----
  224. ======
  225. [[oauth2-client-authorization-code-authorization-request-repository]]
  226. === Storing the Authorization Request
  227. 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).
  228. [TIP]
  229. ====
  230. The `OAuth2AuthorizationRequest` is used to correlate and validate the Authorization Response.
  231. ====
  232. The default implementation of `ServerAuthorizationRequestRepository` is `WebSessionOAuth2ServerAuthorizationRequestRepository`, which stores the `OAuth2AuthorizationRequest` in the `WebSession`.
  233. If you have a custom implementation of `ServerAuthorizationRequestRepository`, you may configure it as shown in the following example:
  234. .ServerAuthorizationRequestRepository Configuration
  235. [tabs]
  236. ======
  237. Java::
  238. +
  239. [source,java,role="primary"]
  240. ----
  241. @Configuration
  242. @EnableWebFluxSecurity
  243. public class OAuth2ClientSecurityConfig {
  244. @Bean
  245. public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
  246. http
  247. .oauth2Client((oauth2) -> oauth2
  248. .authorizationRequestRepository(this.authorizationRequestRepository())
  249. // ...
  250. );
  251. return http.build();
  252. }
  253. }
  254. ----
  255. Kotlin::
  256. +
  257. [source,kotlin,role="secondary"]
  258. ----
  259. @Configuration
  260. @EnableWebFluxSecurity
  261. class OAuth2ClientSecurityConfig {
  262. @Bean
  263. fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  264. http {
  265. oauth2Client {
  266. authorizationRequestRepository = authorizationRequestRepository()
  267. }
  268. }
  269. return http.build()
  270. }
  271. }
  272. ----
  273. ======
  274. [[oauth2-client-authorization-code-access-token]]
  275. === Requesting an Access Token
  276. [NOTE]
  277. ====
  278. 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.
  279. ====
  280. 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.
  281. :section-id: authorization-code
  282. :grant-type: Authorization Code
  283. :class-name: WebClientReactiveAuthorizationCodeTokenResponseClient
  284. :grant-request: OAuth2AuthorizationCodeGrantRequest
  285. :leveloffset: +1
  286. include::partial$reactive/oauth2/client/web-client-access-token-response-client.adoc[]
  287. :leveloffset: -1
  288. [[oauth2-client-authorization-code-access-token-response-client-dsl]]
  289. === Customize using the DSL
  290. Whether you customize `{class-name}` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you can configure it using the DSL (as an alternative to <<oauth2-client-authorization-code-access-token-response-client-bean,publishing a bean>>) as shown in the following example:
  291. .Access Token Response Configuration via DSL
  292. [tabs]
  293. ======
  294. Java::
  295. +
  296. [source,java,role="primary"]
  297. ----
  298. @Configuration
  299. @EnableWebFluxSecurity
  300. public class OAuth2ClientSecurityConfig {
  301. @Bean
  302. public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
  303. http
  304. .oauth2Client((oauth2) -> oauth2
  305. .authenticationManager(this.authorizationCodeAuthenticationManager())
  306. // ...
  307. );
  308. return http.build();
  309. }
  310. private ReactiveAuthenticationManager authorizationCodeAuthenticationManager() {
  311. WebClientReactiveAuthorizationCodeTokenResponseClient accessTokenResponseClient =
  312. new WebClientReactiveAuthorizationCodeTokenResponseClient();
  313. // ...
  314. return new OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient);
  315. }
  316. }
  317. ----
  318. Kotlin::
  319. +
  320. [source,kotlin,role="secondary"]
  321. ----
  322. @Configuration
  323. @EnableWebFluxSecurity
  324. class OAuth2ClientSecurityConfig {
  325. @Bean
  326. fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  327. http {
  328. oauth2Client {
  329. authenticationManager = authorizationCodeAuthenticationManager()
  330. }
  331. }
  332. return http.build()
  333. }
  334. private fun authorizationCodeAuthenticationManager(): ReactiveAuthenticationManager {
  335. val accessTokenResponseClient = WebClientReactiveAuthorizationCodeTokenResponseClient()
  336. // ...
  337. return OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient)
  338. }
  339. }
  340. ----
  341. ======
  342. [[oauth2-client-refresh-token]]
  343. == [[oauth2Client-refresh-token-grant]]Refresh Token
  344. [NOTE]
  345. ====
  346. 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].
  347. ====
  348. [[oauth2-client-refresh-token-access-token]]
  349. === Refreshing an Access Token
  350. [NOTE]
  351. ====
  352. Please refer to the https://tools.ietf.org/html/rfc6749#section-6[Access Token Request/Response] protocol flow for the Refresh Token grant.
  353. ====
  354. 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.
  355. :section-id: refresh-token
  356. :grant-type: Refresh Token
  357. :class-name: WebClientReactiveRefreshTokenTokenResponseClient
  358. :grant-request: OAuth2RefreshTokenGrantRequest
  359. :leveloffset: +1
  360. include::partial$reactive/oauth2/client/web-client-access-token-response-client.adoc[]
  361. :leveloffset: -1
  362. [[oauth2-client-refresh-token-authorized-client-provider-builder]]
  363. === Customize using the Builder
  364. Whether you customize `WebClientReactiveRefreshTokenTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you can configure it using the `ReactiveOAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-refresh-token-access-token-response-client-bean,publishing a bean>>) as follows:
  365. .Access Token Response Configuration via Builder
  366. [tabs]
  367. ======
  368. Java::
  369. +
  370. [source,java,role="primary"]
  371. ----
  372. // Customize
  373. ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient = ...
  374. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  375. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  376. .authorizationCode()
  377. .refreshToken((configurer) -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
  378. .build();
  379. // ...
  380. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  381. ----
  382. Kotlin::
  383. +
  384. [source,kotlin,role="secondary"]
  385. ----
  386. // Customize
  387. val refreshTokenTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> = ...
  388. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  389. .authorizationCode()
  390. .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
  391. .build()
  392. // ...
  393. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  394. ----
  395. ======
  396. [NOTE]
  397. ====
  398. `ReactiveOAuth2AuthorizedClientProviderBuilder.builder().refreshToken()` configures a `RefreshTokenReactiveOAuth2AuthorizedClientProvider`,
  399. which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Refresh Token grant.
  400. ====
  401. The `OAuth2RefreshToken` may optionally be returned in the Access Token Response for the `authorization_code` grant type.
  402. If the `OAuth2AuthorizedClient.getRefreshToken()` is available and the `OAuth2AuthorizedClient.getAccessToken()` is expired, it will automatically be refreshed by the `RefreshTokenReactiveOAuth2AuthorizedClientProvider`.
  403. [[oauth2-client-client-credentials]]
  404. == [[oauth2Client-client-creds-grant]]Client Credentials
  405. [NOTE]
  406. ====
  407. 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.
  408. ====
  409. [[oauth2-client-client-credentials-access-token]]
  410. === Requesting an Access Token
  411. [NOTE]
  412. ====
  413. 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.
  414. ====
  415. 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.
  416. :section-id: client-credentials
  417. :grant-type: Client Credentials
  418. :class-name: WebClientReactiveClientCredentialsTokenResponseClient
  419. :grant-request: OAuth2ClientCredentialsGrantRequest
  420. :leveloffset: +1
  421. include::partial$reactive/oauth2/client/web-client-access-token-response-client.adoc[]
  422. :leveloffset: -1
  423. [[oauth2-client-client-credentials-authorized-client-provider-builder]]
  424. === Customize using the Builder
  425. Whether you customize `WebClientReactiveClientCredentialsTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you can configure it using the `ReactiveOAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-client-credentials-access-token-response-client-bean,publishing a bean>>) as follows:
  426. .Access Token Response Configuration via Builder
  427. [tabs]
  428. ======
  429. Java::
  430. +
  431. [source,java,role="primary"]
  432. ----
  433. // Customize
  434. ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = ...
  435. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  436. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  437. .clientCredentials((configurer) -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
  438. .build();
  439. // ...
  440. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  441. ----
  442. Kotlin::
  443. +
  444. [source,kotlin,role="secondary"]
  445. ----
  446. // Customize
  447. val clientCredentialsTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> = ...
  448. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  449. .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
  450. .build()
  451. // ...
  452. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  453. ----
  454. ======
  455. [NOTE]
  456. ====
  457. `ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsReactiveOAuth2AuthorizedClientProvider`, which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Client Credentials grant.
  458. ====
  459. [[oauth2-client-client-credentials-authorized-client-manager]]
  460. === Using the Access Token
  461. Given the following Spring Boot properties for an OAuth 2.0 Client registration:
  462. [source,yaml]
  463. ----
  464. spring:
  465. security:
  466. oauth2:
  467. client:
  468. registration:
  469. okta:
  470. client-id: okta-client-id
  471. client-secret: okta-client-secret
  472. authorization-grant-type: client_credentials
  473. scope: read, write
  474. provider:
  475. okta:
  476. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  477. ----
  478. ...and the `ReactiveOAuth2AuthorizedClientManager` `@Bean`:
  479. [tabs]
  480. ======
  481. Java::
  482. +
  483. [source,java,role="primary"]
  484. ----
  485. @Bean
  486. public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
  487. ReactiveClientRegistrationRepository clientRegistrationRepository,
  488. ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
  489. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  490. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  491. .clientCredentials()
  492. .build();
  493. DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
  494. new DefaultReactiveOAuth2AuthorizedClientManager(
  495. clientRegistrationRepository, authorizedClientRepository);
  496. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  497. return authorizedClientManager;
  498. }
  499. ----
  500. Kotlin::
  501. +
  502. [source,kotlin,role="secondary"]
  503. ----
  504. @Bean
  505. fun authorizedClientManager(
  506. clientRegistrationRepository: ReactiveClientRegistrationRepository,
  507. authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
  508. val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  509. .clientCredentials()
  510. .build()
  511. val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
  512. clientRegistrationRepository, authorizedClientRepository)
  513. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  514. return authorizedClientManager
  515. }
  516. ----
  517. ======
  518. You may obtain the `OAuth2AccessToken` as follows:
  519. [tabs]
  520. ======
  521. Java::
  522. +
  523. [source,java,role="primary"]
  524. ----
  525. @Controller
  526. public class OAuth2ClientController {
  527. @Autowired
  528. private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
  529. @GetMapping("/")
  530. public Mono<String> index(Authentication authentication, ServerWebExchange exchange) {
  531. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  532. .principal(authentication)
  533. .attribute(ServerWebExchange.class.getName(), exchange)
  534. .build();
  535. return this.authorizedClientManager.authorize(authorizeRequest)
  536. .map(OAuth2AuthorizedClient::getAccessToken)
  537. // ...
  538. .thenReturn("index");
  539. }
  540. }
  541. ----
  542. Kotlin::
  543. +
  544. [source,kotlin,role="secondary"]
  545. ----
  546. class OAuth2ClientController {
  547. @Autowired
  548. private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager
  549. @GetMapping("/")
  550. fun index(authentication: Authentication, exchange: ServerWebExchange): Mono<String> {
  551. val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  552. .principal(authentication)
  553. .attribute(ServerWebExchange::class.java.name, exchange)
  554. .build()
  555. return authorizedClientManager.authorize(authorizeRequest)
  556. .map { it.accessToken }
  557. // ...
  558. .thenReturn("index")
  559. }
  560. }
  561. ----
  562. ======
  563. [NOTE]
  564. ====
  565. `ServerWebExchange` is an OPTIONAL attribute.
  566. 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`.
  567. ====
  568. [[oauth2-client-jwt-bearer]]
  569. == JWT Bearer
  570. [NOTE]
  571. ====
  572. 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.
  573. ====
  574. [[oauth2-client-jwt-bearer-access-token]]
  575. === Requesting an Access Token
  576. [NOTE]
  577. ====
  578. 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.
  579. ====
  580. 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.
  581. :section-id: jwt-bearer
  582. :grant-type: JWT Bearer
  583. :class-name: WebClientReactiveJwtBearerTokenResponseClient
  584. :grant-request: JwtBearerGrantRequest
  585. :leveloffset: +1
  586. include::partial$reactive/oauth2/client/web-client-access-token-response-client.adoc[]
  587. :leveloffset: -1
  588. [[oauth2-client-jwt-bearer-authorized-client-provider-builder]]
  589. === Customize using the Builder
  590. Whether you customize `WebClientReactiveJwtBearerTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you can configure it using the `ReactiveOAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-jwt-bearer-access-token-response-client-bean,publishing a bean>>) as follows:
  591. .Access Token Response Configuration via Builder
  592. [tabs]
  593. ======
  594. Java::
  595. +
  596. [source,java,role="primary"]
  597. ----
  598. // Customize
  599. ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient = ...
  600. JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerReactiveOAuth2AuthorizedClientProvider();
  601. jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);
  602. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  603. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  604. .provider(jwtBearerAuthorizedClientProvider)
  605. .build();
  606. // ...
  607. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  608. ----
  609. Kotlin::
  610. +
  611. [source,kotlin,role="secondary"]
  612. ----
  613. // Customize
  614. val jwtBearerTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> = ...
  615. val jwtBearerAuthorizedClientProvider = JwtBearerReactiveOAuth2AuthorizedClientProvider()
  616. jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient)
  617. val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  618. .provider(jwtBearerAuthorizedClientProvider)
  619. .build()
  620. // ...
  621. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  622. ----
  623. ======
  624. [[oauth2-client-jwt-bearer-authorized-client-manager]]
  625. === Using the Access Token
  626. Given the following Spring Boot properties for an OAuth 2.0 Client registration:
  627. [source,yaml]
  628. ----
  629. spring:
  630. security:
  631. oauth2:
  632. client:
  633. registration:
  634. okta:
  635. client-id: okta-client-id
  636. client-secret: okta-client-secret
  637. authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer
  638. scope: read
  639. provider:
  640. okta:
  641. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  642. ----
  643. ...and the `OAuth2AuthorizedClientManager` `@Bean`:
  644. [tabs]
  645. ======
  646. Java::
  647. +
  648. [source,java,role="primary"]
  649. ----
  650. @Bean
  651. public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
  652. ReactiveClientRegistrationRepository clientRegistrationRepository,
  653. ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
  654. JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider =
  655. new JwtBearerReactiveOAuth2AuthorizedClientProvider();
  656. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  657. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  658. .provider(jwtBearerAuthorizedClientProvider)
  659. .build();
  660. DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
  661. new DefaultReactiveOAuth2AuthorizedClientManager(
  662. clientRegistrationRepository, authorizedClientRepository);
  663. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  664. return authorizedClientManager;
  665. }
  666. ----
  667. Kotlin::
  668. +
  669. [source,kotlin,role="secondary"]
  670. ----
  671. @Bean
  672. fun authorizedClientManager(
  673. clientRegistrationRepository: ReactiveClientRegistrationRepository,
  674. authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
  675. val jwtBearerAuthorizedClientProvider = JwtBearerReactiveOAuth2AuthorizedClientProvider()
  676. val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  677. .provider(jwtBearerAuthorizedClientProvider)
  678. .build()
  679. val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
  680. clientRegistrationRepository, authorizedClientRepository)
  681. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  682. return authorizedClientManager
  683. }
  684. ----
  685. ======
  686. You may obtain the `OAuth2AccessToken` as follows:
  687. [tabs]
  688. ======
  689. Java::
  690. +
  691. [source,java,role="primary"]
  692. ----
  693. @RestController
  694. public class OAuth2ResourceServerController {
  695. @Autowired
  696. private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
  697. @GetMapping("/resource")
  698. public Mono<String> resource(JwtAuthenticationToken jwtAuthentication, ServerWebExchange exchange) {
  699. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  700. .principal(jwtAuthentication)
  701. .build();
  702. return this.authorizedClientManager.authorize(authorizeRequest)
  703. .map(OAuth2AuthorizedClient::getAccessToken)
  704. // ...
  705. .thenReturn("index");
  706. }
  707. }
  708. ----
  709. Kotlin::
  710. +
  711. [source,kotlin,role="secondary"]
  712. ----
  713. class OAuth2ResourceServerController {
  714. @Autowired
  715. private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager
  716. @GetMapping("/resource")
  717. fun resource(jwtAuthentication: JwtAuthenticationToken, exchange: ServerWebExchange): Mono<String> {
  718. val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  719. .principal(jwtAuthentication)
  720. .build()
  721. return authorizedClientManager.authorize(authorizeRequest)
  722. .map { it.accessToken }
  723. // ...
  724. .thenReturn("index")
  725. }
  726. }
  727. ----
  728. ======
  729. [NOTE]
  730. ====
  731. `JwtBearerReactiveOAuth2AuthorizedClientProvider` resolves the `Jwt` assertion via `OAuth2AuthorizationContext.getPrincipal().getPrincipal()` by default, hence the use of `JwtAuthenticationToken` in the preceding example.
  732. ====
  733. [TIP]
  734. ====
  735. If you need to resolve the `Jwt` assertion from a different source, you can provide `JwtBearerReactiveOAuth2AuthorizedClientProvider.setJwtAssertionResolver()` with a custom `Function<OAuth2AuthorizationContext, Mono<Jwt>>`.
  736. ====
  737. [[oauth2-client-token-exchange]]
  738. == [[oauth2Client-token-exchange-grant]]Token Exchange
  739. [NOTE]
  740. ====
  741. Please refer to OAuth 2.0 Token Exchange for further details on the https://datatracker.ietf.org/doc/html/rfc8693[Token Exchange] grant.
  742. ====
  743. [[oauth2-client-token-exchange-access-token]]
  744. === Requesting an Access Token
  745. [NOTE]
  746. ====
  747. Please refer to the https://datatracker.ietf.org/doc/html/rfc8693#section-2[Token Exchange Request and Response] protocol flow for the Token Exchange grant.
  748. ====
  749. The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the Token Exchange grant is `WebClientReactiveTokenExchangeTokenResponseClient`, which uses a `WebClient` when requesting an access token at the Authorization Server’s Token Endpoint.
  750. :section-id: token-exchange
  751. :grant-type: Token Exchange
  752. :class-name: WebClientReactiveTokenExchangeTokenResponseClient
  753. :grant-request: TokenExchangeGrantRequest
  754. :leveloffset: +1
  755. include::partial$reactive/oauth2/client/web-client-access-token-response-client.adoc[]
  756. :leveloffset: -1
  757. [[oauth2-client-token-exchange-authorized-client-provider-builder]]
  758. === Customize using the Builder
  759. Whether you customize `WebClientReactiveTokenExchangeTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you can configure it using the `ReactiveOAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-token-exchange-access-token-response-client-bean,publishing a bean>>) as follows:
  760. .Access Token Response Configuration via Builder
  761. [tabs]
  762. ======
  763. Java::
  764. +
  765. [source,java,role="primary"]
  766. ----
  767. // Customize
  768. ReactiveOAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> tokenExchangeTokenResponseClient = ...
  769. TokenExchangeReactiveOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider = new TokenExchangeReactiveOAuth2AuthorizedClientProvider();
  770. tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient);
  771. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  772. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  773. .provider(tokenExchangeAuthorizedClientProvider)
  774. .build();
  775. // ...
  776. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  777. ----
  778. Kotlin::
  779. +
  780. [source,kotlin,role="secondary"]
  781. ----
  782. // Customize
  783. val tokenExchangeTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> = ...
  784. val tokenExchangeAuthorizedClientProvider = TokenExchangeReactiveOAuth2AuthorizedClientProvider()
  785. tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient)
  786. val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  787. .provider(tokenExchangeAuthorizedClientProvider)
  788. .build()
  789. // ...
  790. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  791. ----
  792. ======
  793. [[oauth2-client-token-exchange-authorized-client-manager]]
  794. === Using the Access Token
  795. Given the following Spring Boot properties for an OAuth 2.0 Client registration:
  796. [source,yaml]
  797. ----
  798. spring:
  799. security:
  800. oauth2:
  801. client:
  802. registration:
  803. okta:
  804. client-id: okta-client-id
  805. client-secret: okta-client-secret
  806. authorization-grant-type: urn:ietf:params:oauth:grant-type:token-exchange
  807. scope: read
  808. provider:
  809. okta:
  810. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  811. ----
  812. ...and the `OAuth2AuthorizedClientManager` `@Bean`:
  813. [tabs]
  814. ======
  815. Java::
  816. +
  817. [source,java,role="primary"]
  818. ----
  819. @Bean
  820. public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
  821. ReactiveClientRegistrationRepository clientRegistrationRepository,
  822. ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
  823. TokenExchangeReactiveOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider =
  824. new TokenExchangeReactiveOAuth2AuthorizedClientProvider();
  825. ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
  826. ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  827. .provider(tokenExchangeAuthorizedClientProvider)
  828. .build();
  829. DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
  830. new DefaultReactiveOAuth2AuthorizedClientManager(
  831. clientRegistrationRepository, authorizedClientRepository);
  832. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  833. return authorizedClientManager;
  834. }
  835. ----
  836. Kotlin::
  837. +
  838. [source,kotlin,role="secondary"]
  839. ----
  840. @Bean
  841. fun authorizedClientManager(
  842. clientRegistrationRepository: ReactiveClientRegistrationRepository,
  843. authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
  844. val tokenExchangeAuthorizedClientProvider = TokenExchangeReactiveOAuth2AuthorizedClientProvider()
  845. val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
  846. .provider(tokenExchangeAuthorizedClientProvider)
  847. .build()
  848. val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
  849. clientRegistrationRepository, authorizedClientRepository)
  850. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  851. return authorizedClientManager
  852. }
  853. ----
  854. ======
  855. You may obtain the `OAuth2AccessToken` as follows:
  856. [tabs]
  857. ======
  858. Java::
  859. +
  860. [source,java,role="primary"]
  861. ----
  862. @RestController
  863. public class OAuth2ResourceServerController {
  864. @Autowired
  865. private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
  866. @GetMapping("/resource")
  867. public Mono<String> resource(JwtAuthenticationToken jwtAuthentication) {
  868. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  869. .principal(jwtAuthentication)
  870. .build();
  871. return this.authorizedClientManager.authorize(authorizeRequest)
  872. .map(OAuth2AuthorizedClient::getAccessToken)
  873. // ...
  874. .thenReturn("index");
  875. }
  876. }
  877. ----
  878. Kotlin::
  879. +
  880. [source,kotlin,role="secondary"]
  881. ----
  882. class OAuth2ResourceServerController {
  883. @Autowired
  884. private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager
  885. @GetMapping("/resource")
  886. fun resource(jwtAuthentication: JwtAuthenticationToken): Mono<String> {
  887. val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  888. .principal(jwtAuthentication)
  889. .build()
  890. return authorizedClientManager.authorize(authorizeRequest)
  891. .map { it.accessToken }
  892. // ...
  893. .thenReturn("index")
  894. }
  895. }
  896. ----
  897. ======
  898. [NOTE]
  899. ====
  900. `TokenExchangeReactiveOAuth2AuthorizedClientProvider` resolves the subject token (as an `OAuth2Token`) via `OAuth2AuthorizationContext.getPrincipal().getPrincipal()` by default, hence the use of `JwtAuthenticationToken` in the preceding example.
  901. An actor token is not resolved by default.
  902. ====
  903. [TIP]
  904. ====
  905. If you need to resolve the subject token from a different source, you can provide `TokenExchangeReactiveOAuth2AuthorizedClientProvider.setSubjectTokenResolver()` with a custom `Function<OAuth2AuthorizationContext, Mono<OAuth2Token>>`.
  906. ====
  907. [TIP]
  908. ====
  909. If you need to resolve an actor token, you can provide `TokenExchangeReactiveOAuth2AuthorizedClientProvider.setActorTokenResolver()` with a custom `Function<OAuth2AuthorizationContext, Mono<OAuth2Token>>`.
  910. ====