authorization-grants.adoc 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. [[oauth2-client-authorization-grants]]
  2. = [[oauth2Client-auth-grant-support]]Authorization Grant Support
  3. :spring-security-reference-base-url: https://docs.spring.io/spring-security/reference
  4. This section describes Spring Security's support for authorization grants.
  5. [[oauth2-client-authorization-code]]
  6. == [[oauth2Client-auth-code-grant]]Authorization Code
  7. [NOTE]
  8. ====
  9. See the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] grant.
  10. ====
  11. [[oauth2-client-authorization-code-authorization]]
  12. === Obtaining Authorization
  13. [NOTE]
  14. ====
  15. See the https://tools.ietf.org/html/rfc6749#section-4.1.1[Authorization Request/Response] protocol flow for the Authorization Code grant.
  16. ====
  17. [[oauth2-client-authorization-code-authorization-request]]
  18. === Initiating the Authorization Request
  19. The `OAuth2AuthorizationRequestRedirectFilter` uses an `OAuth2AuthorizationRequestResolver` 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.
  20. The primary role of the `OAuth2AuthorizationRequestResolver` is to resolve an `OAuth2AuthorizationRequest` from the provided web request.
  21. The default implementation `DefaultOAuth2AuthorizationRequestResolver` matches on the (default) path `+/oauth2/authorization/{registrationId}+`, extracting the `registrationId`, and using it to build the `OAuth2AuthorizationRequest` for the associated `ClientRegistration`.
  22. Consider the following Spring Boot properties for an OAuth 2.0 Client registration:
  23. [source,yaml,attrs="-attributes"]
  24. ----
  25. spring:
  26. security:
  27. oauth2:
  28. client:
  29. registration:
  30. okta:
  31. client-id: okta-client-id
  32. client-secret: okta-client-secret
  33. authorization-grant-type: authorization_code
  34. redirect-uri: "{baseUrl}/authorized/okta"
  35. scope: read, write
  36. provider:
  37. okta:
  38. authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize
  39. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  40. ----
  41. Given the preceding properties, a request with the base path `/oauth2/authorization/okta` initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectFilter` and ultimately starts the Authorization Code grant flow.
  42. [NOTE]
  43. ====
  44. The `AuthorizationCodeOAuth2AuthorizedClientProvider` is an implementation of `OAuth2AuthorizedClientProvider` for the Authorization Code grant,
  45. which also initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectFilter`.
  46. ====
  47. If the OAuth 2.0 Client is a https://tools.ietf.org/html/rfc6749#section-2.1[Public Client], configure the OAuth 2.0 Client registration as follows:
  48. [source,yaml,attrs="-attributes"]
  49. ----
  50. spring:
  51. security:
  52. oauth2:
  53. client:
  54. registration:
  55. okta:
  56. client-id: okta-client-id
  57. client-authentication-method: none
  58. authorization-grant-type: authorization_code
  59. redirect-uri: "{baseUrl}/authorized/okta"
  60. # ...
  61. ----
  62. Public Clients are supported by using https://tools.ietf.org/html/rfc7636[Proof Key for Code Exchange] (PKCE).
  63. If the client is running in an untrusted environment (such as a native application or web browser-based application) and is therefore incapable of maintaining the confidentiality of its credentials, PKCE is automatically used when the following conditions are true:
  64. . `client-secret` is omitted (or empty) and
  65. . `client-authentication-method` is set to `none` (`ClientAuthenticationMethod.NONE`)
  66. or
  67. . When `ClientRegistration.clientSettings.requireProofKey` is `true` (in this case `ClientRegistration.authorizationGrantType` must be `authorization_code`)
  68. [TIP]
  69. ====
  70. 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 `DefaultOAuth2AuthorizationRequestResolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce())`.
  71. ====
  72. [[oauth2-client-authorization-code-redirect-uri]]
  73. [[oauth2Client-auth-code-redirect-uri]]The `DefaultOAuth2AuthorizationRequestResolver` also supports `URI` template variables for the `redirect-uri` by using `UriComponentsBuilder`.
  74. The following configuration uses all the supported `URI` template variables:
  75. [source,yaml,attrs="-attributes"]
  76. ----
  77. spring:
  78. security:
  79. oauth2:
  80. client:
  81. registration:
  82. okta:
  83. # ...
  84. redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}"
  85. # ...
  86. ----
  87. [NOTE]
  88. ====
  89. `+{baseUrl}+` resolves to `+{baseScheme}://{baseHost}{basePort}{basePath}+`
  90. ====
  91. 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].
  92. Doing so ensures that the `X-Forwarded-*` headers are used when expanding the `redirect-uri`.
  93. [[oauth2-client-authorization-code-authorization-request-resolver]]
  94. === Customizing the Authorization Request
  95. One of the primary use cases an `OAuth2AuthorizationRequestResolver` 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.
  96. 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].
  97. One of those extended parameters is the `prompt` parameter.
  98. [NOTE]
  99. ====
  100. 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`.
  101. ====
  102. The following example shows how to configure the `DefaultOAuth2AuthorizationRequestResolver` with a `Consumer<OAuth2AuthorizationRequest.Builder>` that customizes the Authorization Request for `oauth2Login()`, by including the request parameter `prompt=consent`.
  103. [tabs]
  104. ======
  105. Java::
  106. +
  107. [source,java,role="primary"]
  108. ----
  109. @Configuration
  110. @EnableWebSecurity
  111. public class OAuth2LoginSecurityConfig {
  112. @Autowired
  113. private ClientRegistrationRepository clientRegistrationRepository;
  114. @Bean
  115. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  116. http
  117. .authorizeHttpRequests((authorize) -> authorize
  118. .anyRequest().authenticated()
  119. )
  120. .oauth2Login((oauth2) -> oauth2
  121. .authorizationEndpoint((authorization) -> authorization
  122. .authorizationRequestResolver(
  123. authorizationRequestResolver(this.clientRegistrationRepository)
  124. )
  125. )
  126. );
  127. return http.build();
  128. }
  129. private OAuth2AuthorizationRequestResolver authorizationRequestResolver(
  130. ClientRegistrationRepository clientRegistrationRepository) {
  131. DefaultOAuth2AuthorizationRequestResolver authorizationRequestResolver =
  132. new DefaultOAuth2AuthorizationRequestResolver(
  133. clientRegistrationRepository, "/oauth2/authorization");
  134. authorizationRequestResolver.setAuthorizationRequestCustomizer(
  135. authorizationRequestCustomizer());
  136. return authorizationRequestResolver;
  137. }
  138. private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
  139. return customizer -> customizer
  140. .additionalParameters((params) -> params.put("prompt", "consent"));
  141. }
  142. }
  143. ----
  144. Kotlin::
  145. +
  146. [source,kotlin,role="secondary"]
  147. ----
  148. @Configuration
  149. @EnableWebSecurity
  150. class SecurityConfig {
  151. @Autowired
  152. private lateinit var customClientRegistrationRepository: ClientRegistrationRepository
  153. @Bean
  154. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  155. http {
  156. authorizeRequests {
  157. authorize(anyRequest, authenticated)
  158. }
  159. oauth2Login {
  160. authorizationEndpoint {
  161. authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
  162. }
  163. }
  164. }
  165. return http.build()
  166. }
  167. private fun authorizationRequestResolver(
  168. clientRegistrationRepository: ClientRegistrationRepository?): OAuth2AuthorizationRequestResolver {
  169. val authorizationRequestResolver = DefaultOAuth2AuthorizationRequestResolver(
  170. clientRegistrationRepository, "/oauth2/authorization")
  171. authorizationRequestResolver.setAuthorizationRequestCustomizer(
  172. authorizationRequestCustomizer())
  173. return authorizationRequestResolver
  174. }
  175. private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
  176. return Consumer { customizer ->
  177. customizer
  178. .additionalParameters { params -> params["prompt"] = "consent" }
  179. }
  180. }
  181. }
  182. ----
  183. ======
  184. For the simple use case where the additional request parameter is always the same for a specific provider, you can add it directly in the `authorization-uri` property.
  185. For example, if the value for the request parameter `prompt` is always `consent` for the provider `okta`, you can configure it as follows:
  186. [source,yaml]
  187. ----
  188. spring:
  189. security:
  190. oauth2:
  191. client:
  192. provider:
  193. okta:
  194. authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent
  195. ----
  196. The preceding example shows the common use case of adding a custom parameter on top of the standard parameters.
  197. Alternatively, if your requirements are more advanced, you can take full control in building the Authorization Request URI by overriding the `OAuth2AuthorizationRequest.authorizationRequestUri` property.
  198. [TIP]
  199. ====
  200. `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.
  201. ====
  202. The following example shows a variation of `authorizationRequestCustomizer()` from the preceding example and instead overrides the `OAuth2AuthorizationRequest.authorizationRequestUri` property:
  203. [tabs]
  204. ======
  205. Java::
  206. +
  207. [source,java,role="primary"]
  208. ----
  209. private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
  210. return customizer -> customizer
  211. .authorizationRequestUri((uriBuilder) -> uriBuilder
  212. .queryParam("prompt", "consent").build());
  213. }
  214. ----
  215. Kotlin::
  216. +
  217. [source,kotlin,role="secondary"]
  218. ----
  219. private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
  220. return Consumer { customizer: OAuth2AuthorizationRequest.Builder ->
  221. customizer
  222. .authorizationRequestUri { uriBuilder: UriBuilder ->
  223. uriBuilder
  224. .queryParam("prompt", "consent").build()
  225. }
  226. }
  227. }
  228. ----
  229. ======
  230. [[oauth2-client-authorization-code-authorization-request-repository]]
  231. === Storing the Authorization Request
  232. The `AuthorizationRequestRepository` 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).
  233. [TIP]
  234. ====
  235. The `OAuth2AuthorizationRequest` is used to correlate and validate the Authorization Response.
  236. ====
  237. The default implementation of `AuthorizationRequestRepository` is `HttpSessionOAuth2AuthorizationRequestRepository`, which stores the `OAuth2AuthorizationRequest` in the `HttpSession`.
  238. If you have a custom implementation of `AuthorizationRequestRepository`, you can configure it as follows:
  239. .AuthorizationRequestRepository Configuration
  240. [tabs]
  241. ======
  242. Java::
  243. +
  244. [source,java,role="primary"]
  245. ----
  246. @Configuration
  247. @EnableWebSecurity
  248. public class OAuth2ClientSecurityConfig {
  249. @Bean
  250. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  251. http
  252. .oauth2Client((oauth2) -> oauth2
  253. .authorizationCodeGrant((codeGrant) -> codeGrant
  254. .authorizationRequestRepository(this.authorizationRequestRepository())
  255. // ...
  256. )
  257. )
  258. .oauth2Login((oauth2) -> oauth2
  259. .authorizationEndpoint((endpoint) -> endpoint
  260. .authorizationRequestRepository(this.authorizationRequestRepository())
  261. // ...
  262. )
  263. );
  264. return http.build();
  265. }
  266. @Bean
  267. public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
  268. return new CustomOAuth2AuthorizationRequestRepository();
  269. }
  270. }
  271. ----
  272. Kotlin::
  273. +
  274. [source,kotlin,role="secondary"]
  275. ----
  276. @Configuration
  277. @EnableWebSecurity
  278. class OAuth2ClientSecurityConfig {
  279. @Bean
  280. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  281. http {
  282. oauth2Client {
  283. authorizationCodeGrant {
  284. authorizationRequestRepository = authorizationRequestRepository()
  285. }
  286. }
  287. }
  288. return http.build()
  289. }
  290. }
  291. ----
  292. Xml::
  293. +
  294. [source,xml,role="secondary"]
  295. ----
  296. <http>
  297. <oauth2-client>
  298. <authorization-code-grant authorization-request-repository-ref="authorizationRequestRepository"/>
  299. </oauth2-client>
  300. </http>
  301. ----
  302. ======
  303. [[oauth2-client-authorization-code-access-token]]
  304. === Requesting an Access Token
  305. [NOTE]
  306. ====
  307. See the https://tools.ietf.org/html/rfc6749#section-4.1.3[Access Token Request/Response] protocol flow for the Authorization Code grant.
  308. ====
  309. There are two implementations of `OAuth2AccessTokenResponseClient` that can be used to make HTTP requests to the Token Endpoint in order to obtain an access token for the Authorization Code grant:
  310. * `DefaultAuthorizationCodeTokenResponseClient` (_default_)
  311. * `RestClientAuthorizationCodeTokenResponseClient`
  312. The default implementation uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint.
  313. Spring Security 6.4 introduces a new implementation based on `RestClient`, which provides similar functionality but is better aligned with the Reactive version of the component (based on `WebClient`) in order to provide consistent configuration for applications on either stack.
  314. [NOTE]
  315. ====
  316. This section focuses on `RestClientAuthorizationCodeTokenResponseClient`.
  317. You can read about {spring-security-reference-base-url}/6.3/servlet/oauth2/client/authorization-grants.html#_requesting_an_access_token[`DefaultAuthorizationCodeTokenResponseClient`] in the Spring Security 6.3 documentation.
  318. ====
  319. :section-id: authorization-code
  320. :grant-type: Authorization Code
  321. :class-name: RestClientAuthorizationCodeTokenResponseClient
  322. :grant-request: OAuth2AuthorizationCodeGrantRequest
  323. :leveloffset: +1
  324. include::partial$servlet/oauth2/client/rest-client-access-token-response-client.adoc[]
  325. :leveloffset: -1
  326. [[oauth2-client-authorization-code-access-token-response-client-dsl]]
  327. === Customize using the DSL
  328. Whether you customize `{class-name}` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you can configure it using the DSL (as an alternative to <<oauth2-client-authorization-code-access-token-response-client-bean,publishing a bean>>) as follows:
  329. .Access Token Response Configuration via DSL
  330. [tabs]
  331. ======
  332. Java::
  333. +
  334. [source,java,role="primary"]
  335. ----
  336. @Configuration
  337. @EnableWebSecurity
  338. public class OAuth2ClientSecurityConfig {
  339. @Bean
  340. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  341. http
  342. .oauth2Client((oauth2) -> oauth2
  343. .authorizationCodeGrant((codeGrant) -> codeGrant
  344. .accessTokenResponseClient(this.accessTokenResponseClient())
  345. // ...
  346. )
  347. );
  348. return http.build();
  349. }
  350. }
  351. ----
  352. Kotlin::
  353. +
  354. [source,kotlin,role="secondary"]
  355. ----
  356. @Configuration
  357. @EnableWebSecurity
  358. class OAuth2ClientSecurityConfig {
  359. @Bean
  360. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  361. http {
  362. oauth2Client {
  363. authorizationCodeGrant {
  364. accessTokenResponseClient = accessTokenResponseClient()
  365. }
  366. }
  367. }
  368. return http.build()
  369. }
  370. }
  371. ----
  372. Xml::
  373. +
  374. [source,xml,role="secondary"]
  375. ----
  376. <http>
  377. <oauth2-client>
  378. <authorization-code-grant access-token-response-client-ref="accessTokenResponseClient"/>
  379. </oauth2-client>
  380. </http>
  381. ----
  382. ======
  383. [[oauth2-client-refresh-token]]
  384. == [[oauth2Client-refresh-token-grant]]Refresh Token
  385. [NOTE]
  386. ====
  387. See the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.5[Refresh Token].
  388. ====
  389. [[oauth2-client-refresh-token-access-token]]
  390. === Refreshing an Access Token
  391. [NOTE]
  392. ====
  393. See the https://tools.ietf.org/html/rfc6749#section-6[Access Token Request/Response] protocol flow for the Refresh Token grant.
  394. ====
  395. There are two implementations of `OAuth2AccessTokenResponseClient` that can be used to make HTTP requests to the Token Endpoint in order to obtain an access token for the Refresh Token grant:
  396. * `DefaultRefreshTokenTokenResponseClient` (_default_)
  397. * `RestClientRefreshTokenTokenResponseClient`
  398. The default implementation uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint.
  399. Spring Security 6.4 introduces a new implementation based on `RestClient`, which provides similar functionality but is better aligned with the Reactive version of the component (based on `WebClient`) in order to provide consistent configuration for applications on either stack.
  400. [NOTE]
  401. ====
  402. This section focuses on `RestClientRefreshTokenTokenResponseClient`.
  403. You can read about {spring-security-reference-base-url}/6.3/servlet/oauth2/client/authorization-grants.html#_refreshing_an_access_token[`DefaultRefreshTokenTokenResponseClient`] in the Spring Security 6.3 documentation.
  404. ====
  405. :section-id: refresh-token
  406. :grant-type: Refresh Token
  407. :class-name: RestClientRefreshTokenTokenResponseClient
  408. :grant-request: OAuth2RefreshTokenGrantRequest
  409. :leveloffset: +1
  410. include::partial$servlet/oauth2/client/rest-client-access-token-response-client.adoc[]
  411. :leveloffset: -1
  412. [[oauth2-client-refresh-token-authorized-client-provider-builder]]
  413. === Customize using the Builder
  414. Whether you customize `RestClientRefreshTokenTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you can configure it using the `OAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-refresh-token-access-token-response-client-bean,publishing a bean>>) as follows:
  415. .Access Token Response Configuration via Builder
  416. [tabs]
  417. ======
  418. Java::
  419. +
  420. [source,java,role="primary"]
  421. ----
  422. // Customize
  423. OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient = ...
  424. OAuth2AuthorizedClientProvider authorizedClientProvider =
  425. OAuth2AuthorizedClientProviderBuilder.builder()
  426. .authorizationCode()
  427. .refreshToken((configurer) -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
  428. .build();
  429. // ...
  430. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  431. ----
  432. Kotlin::
  433. +
  434. [source,kotlin,role="secondary"]
  435. ----
  436. // Customize
  437. val refreshTokenTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> = ...
  438. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  439. .authorizationCode()
  440. .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
  441. .build()
  442. // ...
  443. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  444. ----
  445. ======
  446. [NOTE]
  447. ====
  448. `OAuth2AuthorizedClientProviderBuilder.builder().refreshToken()` configures a `RefreshTokenOAuth2AuthorizedClientProvider`,
  449. which is an implementation of an `OAuth2AuthorizedClientProvider` for the Refresh Token grant.
  450. ====
  451. The `OAuth2RefreshToken` can optionally be returned in the Access Token Response for the `authorization_code` and `password` grant types.
  452. If the `OAuth2AuthorizedClient.getRefreshToken()` is available and the `OAuth2AuthorizedClient.getAccessToken()` is expired, it is automatically refreshed by the `RefreshTokenOAuth2AuthorizedClientProvider`.
  453. [[oauth2-client-client-credentials]]
  454. == [[oauth2Client-client-creds-grant]]Client Credentials
  455. [NOTE]
  456. ====
  457. 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.
  458. ====
  459. [[oauth2-client-client-credentials-access-token]]
  460. === Requesting an Access Token
  461. [NOTE]
  462. ====
  463. See the https://tools.ietf.org/html/rfc6749#section-4.4.2[Access Token Request/Response] protocol flow for the Client Credentials grant.
  464. ====
  465. There are two implementations of `OAuth2AccessTokenResponseClient` that can be used to make HTTP requests to the Token Endpoint in order to obtain an access token for the Client Credentials grant:
  466. * `DefaultClientCredentialsTokenResponseClient` (_default_)
  467. * `RestClientClientCredentialsTokenResponseClient`
  468. The default implementation uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint.
  469. Spring Security 6.4 introduces a new implementation based on `RestClient`, which provides similar functionality but is better aligned with the Reactive version of the component (based on `WebClient`) in order to provide consistent configuration for applications on either stack.
  470. [NOTE]
  471. ====
  472. This section focuses on `RestClientClientCredentialsTokenResponseClient`.
  473. You can read about {spring-security-reference-base-url}/6.3/servlet/oauth2/client/authorization-grants.html#_requesting_an_access_token_2[`DefaultClientCredentialsTokenResponseClient`] in the Spring Security 6.3 documentation.
  474. ====
  475. :section-id: client-credentials
  476. :grant-type: Client Credentials
  477. :class-name: RestClientClientCredentialsTokenResponseClient
  478. :grant-request: OAuth2ClientCredentialsGrantRequest
  479. :leveloffset: +1
  480. include::partial$servlet/oauth2/client/rest-client-access-token-response-client.adoc[]
  481. :leveloffset: -1
  482. [[oauth2-client-client-credentials-authorized-client-provider-builder]]
  483. === Customize using the Builder
  484. Whether you customize `RestClientClientCredentialsTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you can configure it using the `OAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-client-credentials-access-token-response-client-bean,publishing a bean>>) as follows:
  485. .Access Token Response Configuration via Builder
  486. [tabs]
  487. ======
  488. Java::
  489. +
  490. [source,java,role="primary"]
  491. ----
  492. // Customize
  493. OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = ...
  494. OAuth2AuthorizedClientProvider authorizedClientProvider =
  495. OAuth2AuthorizedClientProviderBuilder.builder()
  496. .clientCredentials((configurer) -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
  497. .build();
  498. // ...
  499. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  500. ----
  501. Kotlin::
  502. +
  503. [source,kotlin,role="secondary"]
  504. ----
  505. // Customize
  506. val clientCredentialsTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> = ...
  507. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  508. .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
  509. .build()
  510. // ...
  511. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  512. ----
  513. ======
  514. [NOTE]
  515. ====
  516. `OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsOAuth2AuthorizedClientProvider`,
  517. which is an implementation of an `OAuth2AuthorizedClientProvider` for the Client Credentials grant.
  518. ====
  519. [[oauth2-client-client-credentials-authorized-client-manager]]
  520. === Using the Access Token
  521. Consider the following Spring Boot properties for an OAuth 2.0 Client registration:
  522. [source,yaml]
  523. ----
  524. spring:
  525. security:
  526. oauth2:
  527. client:
  528. registration:
  529. okta:
  530. client-id: okta-client-id
  531. client-secret: okta-client-secret
  532. authorization-grant-type: client_credentials
  533. scope: read, write
  534. provider:
  535. okta:
  536. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  537. ----
  538. Further consider the following `OAuth2AuthorizedClientManager` `@Bean`:
  539. [tabs]
  540. ======
  541. Java::
  542. +
  543. [source,java,role="primary"]
  544. ----
  545. @Bean
  546. public OAuth2AuthorizedClientManager authorizedClientManager(
  547. ClientRegistrationRepository clientRegistrationRepository,
  548. OAuth2AuthorizedClientRepository authorizedClientRepository) {
  549. OAuth2AuthorizedClientProvider authorizedClientProvider =
  550. OAuth2AuthorizedClientProviderBuilder.builder()
  551. .clientCredentials()
  552. .build();
  553. DefaultOAuth2AuthorizedClientManager authorizedClientManager =
  554. new DefaultOAuth2AuthorizedClientManager(
  555. clientRegistrationRepository, authorizedClientRepository);
  556. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  557. return authorizedClientManager;
  558. }
  559. ----
  560. Kotlin::
  561. +
  562. [source,kotlin,role="secondary"]
  563. ----
  564. @Bean
  565. fun authorizedClientManager(
  566. clientRegistrationRepository: ClientRegistrationRepository,
  567. authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
  568. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  569. .clientCredentials()
  570. .build()
  571. val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
  572. clientRegistrationRepository, authorizedClientRepository)
  573. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  574. return authorizedClientManager
  575. }
  576. ----
  577. ======
  578. Given the preceding properties and bean, you can obtain the `OAuth2AccessToken` as follows:
  579. [tabs]
  580. ======
  581. Java::
  582. +
  583. [source,java,role="primary"]
  584. ----
  585. @Controller
  586. public class OAuth2ClientController {
  587. @Autowired
  588. private OAuth2AuthorizedClientManager authorizedClientManager;
  589. @GetMapping("/")
  590. public String index(Authentication authentication,
  591. HttpServletRequest servletRequest,
  592. HttpServletResponse servletResponse) {
  593. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  594. .principal(authentication)
  595. .attributes(attrs -> {
  596. attrs.put(HttpServletRequest.class.getName(), servletRequest);
  597. attrs.put(HttpServletResponse.class.getName(), servletResponse);
  598. })
  599. .build();
  600. OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
  601. OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
  602. // ...
  603. return "index";
  604. }
  605. }
  606. ----
  607. Kotlin::
  608. +
  609. [source,kotlin,role="secondary"]
  610. ----
  611. class OAuth2ClientController {
  612. @Autowired
  613. private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
  614. @GetMapping("/")
  615. fun index(authentication: Authentication?,
  616. servletRequest: HttpServletRequest,
  617. servletResponse: HttpServletResponse): String {
  618. val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  619. .principal(authentication)
  620. .attributes(Consumer { attrs: MutableMap<String, Any> ->
  621. attrs[HttpServletRequest::class.java.name] = servletRequest
  622. attrs[HttpServletResponse::class.java.name] = servletResponse
  623. })
  624. .build()
  625. val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
  626. val accessToken: OAuth2AccessToken = authorizedClient.accessToken
  627. // ...
  628. return "index"
  629. }
  630. }
  631. ----
  632. ======
  633. [NOTE]
  634. ====
  635. `HttpServletRequest` and `HttpServletResponse` are both OPTIONAL attributes.
  636. If not provided, they default to `ServletRequestAttributes` by using `RequestContextHolder.getRequestAttributes()`.
  637. ====
  638. [[oauth2-client-password]]
  639. == [[oauth2Client-password-grant]]Resource Owner Password Credentials
  640. [NOTE]
  641. ====
  642. See 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.
  643. ====
  644. [[oauth2-client-password-access-token]]
  645. === Requesting an Access Token
  646. [NOTE]
  647. ====
  648. See the https://tools.ietf.org/html/rfc6749#section-4.3.2[Access Token Request/Response] protocol flow for the Resource Owner Password Credentials grant.
  649. ====
  650. The default implementation of `OAuth2AccessTokenResponseClient` for the Resource Owner Password Credentials grant is `DefaultPasswordTokenResponseClient`, which uses a `RestOperations` when requesting an access token at the Authorization Server’s Token Endpoint.
  651. [CAUTION]
  652. ====
  653. The `DefaultPasswordTokenResponseClient` class and support for the Resource Owner Password Credentials grant are deprecated.
  654. This section will be removed in Spring Security 7.
  655. ====
  656. The `DefaultPasswordTokenResponseClient` is flexible, as it lets you customize the pre-processing of the Token Request or post-handling of the Token Response.
  657. [[oauth2-client-password-access-token-request]]
  658. === Customizing the Access Token Request
  659. If you need to customize the pre-processing of the Token Request, you can provide `DefaultPasswordTokenResponseClient.setRequestEntityConverter()` with a custom `Converter<OAuth2PasswordGrantRequest, RequestEntity<?>>`.
  660. The default implementation (`OAuth2PasswordGrantRequestEntityConverter`) builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-4.3.2[OAuth 2.0 Access Token Request].
  661. However, providing a custom `Converter` would let you extend the standard Token Request and add custom parameter(s).
  662. To customize only the parameters of the request, you can provide `OAuth2PasswordGrantRequestEntityConverter.setParametersConverter()` with a custom `Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>` to completely override the parameters sent with the request. This is often simpler than constructing a `RequestEntity` directly.
  663. [TIP]
  664. ====
  665. If you prefer to only add additional parameters, you can provide `OAuth2PasswordGrantRequestEntityConverter.addParametersConverter()` with a custom `Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>` which constructs an aggregate `Converter`.
  666. ====
  667. [IMPORTANT]
  668. ====
  669. The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.
  670. ====
  671. [[oauth2-client-password-access-token-response]]
  672. === Customizing the Access Token Response
  673. On the other end, if you need to customize the post-handling of the Token Response, you need to provide `DefaultPasswordTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`.
  674. The default `RestOperations` is configured as follows:
  675. [tabs]
  676. ======
  677. Java::
  678. +
  679. [source,java,role="primary"]
  680. ----
  681. RestTemplate restTemplate = new RestTemplate(Arrays.asList(
  682. new FormHttpMessageConverter(),
  683. new OAuth2AccessTokenResponseHttpMessageConverter()));
  684. restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
  685. ----
  686. Kotlin::
  687. +
  688. [source,kotlin,role="secondary"]
  689. ----
  690. val restTemplate = RestTemplate(listOf(
  691. FormHttpMessageConverter(),
  692. OAuth2AccessTokenResponseHttpMessageConverter()))
  693. restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
  694. ----
  695. ======
  696. [TIP]
  697. ====
  698. Spring MVC `FormHttpMessageConverter` is required, as it is used when sending the OAuth 2.0 Access Token Request.
  699. ====
  700. `OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response.
  701. You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setTokenResponseConverter()` with a custom `Converter<Map<String, String>, OAuth2AccessTokenResponse>` that is used to convert the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`.
  702. `OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, such as `400 Bad Request`.
  703. It uses an `OAuth2ErrorHttpMessageConverter` to convert the OAuth 2.0 Error parameters to an `OAuth2Error`.
  704. [[oauth2-client-password-authorized-client-provider-builder]]
  705. === Customize using the Builder
  706. Whether you customize `DefaultPasswordTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you need to configure it as follows:
  707. .Access Token Response Configuration via Builder
  708. [tabs]
  709. ======
  710. Java::
  711. +
  712. [source,java,role="primary"]
  713. ----
  714. // Customize
  715. OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient = ...
  716. OAuth2AuthorizedClientProvider authorizedClientProvider =
  717. OAuth2AuthorizedClientProviderBuilder.builder()
  718. .password((configurer) -> configurer.accessTokenResponseClient(passwordTokenResponseClient))
  719. .refreshToken()
  720. .build();
  721. // ...
  722. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  723. ----
  724. Kotlin::
  725. +
  726. [source,kotlin,role="secondary"]
  727. ----
  728. val passwordTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...
  729. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  730. .password { it.accessTokenResponseClient(passwordTokenResponseClient) }
  731. .refreshToken()
  732. .build()
  733. // ...
  734. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  735. ----
  736. ======
  737. [NOTE]
  738. ====
  739. `OAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordOAuth2AuthorizedClientProvider`,
  740. which is an implementation of an `OAuth2AuthorizedClientProvider` for the Resource Owner Password Credentials grant.
  741. ====
  742. [[oauth2-client-password-authorized-client-manager]]
  743. === Using the Access Token
  744. Consider the following Spring Boot properties for an OAuth 2.0 Client registration:
  745. [source,yaml]
  746. ----
  747. spring:
  748. security:
  749. oauth2:
  750. client:
  751. registration:
  752. okta:
  753. client-id: okta-client-id
  754. client-secret: okta-client-secret
  755. authorization-grant-type: password
  756. scope: read, write
  757. provider:
  758. okta:
  759. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  760. ----
  761. Further consider the `OAuth2AuthorizedClientManager` `@Bean`:
  762. [tabs]
  763. ======
  764. Java::
  765. +
  766. [source,java,role="primary"]
  767. ----
  768. @Bean
  769. public OAuth2AuthorizedClientManager authorizedClientManager(
  770. ClientRegistrationRepository clientRegistrationRepository,
  771. OAuth2AuthorizedClientRepository authorizedClientRepository) {
  772. OAuth2AuthorizedClientProvider authorizedClientProvider =
  773. OAuth2AuthorizedClientProviderBuilder.builder()
  774. .password()
  775. .refreshToken()
  776. .build();
  777. DefaultOAuth2AuthorizedClientManager authorizedClientManager =
  778. new DefaultOAuth2AuthorizedClientManager(
  779. clientRegistrationRepository, authorizedClientRepository);
  780. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  781. // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
  782. // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
  783. authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());
  784. return authorizedClientManager;
  785. }
  786. private Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper() {
  787. return authorizeRequest -> {
  788. Map<String, Object> contextAttributes = Collections.emptyMap();
  789. HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
  790. String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
  791. String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
  792. if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
  793. contextAttributes = new HashMap<>();
  794. // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
  795. contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
  796. contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
  797. }
  798. return contextAttributes;
  799. };
  800. }
  801. ----
  802. Kotlin::
  803. +
  804. [source,kotlin,role="secondary"]
  805. ----
  806. @Bean
  807. fun authorizedClientManager(
  808. clientRegistrationRepository: ClientRegistrationRepository,
  809. authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
  810. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  811. .password()
  812. .refreshToken()
  813. .build()
  814. val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
  815. clientRegistrationRepository, authorizedClientRepository)
  816. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  817. // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
  818. // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
  819. authorizedClientManager.setContextAttributesMapper(contextAttributesMapper())
  820. return authorizedClientManager
  821. }
  822. private fun contextAttributesMapper(): Function<OAuth2AuthorizeRequest, MutableMap<String, Any>> {
  823. return Function { authorizeRequest ->
  824. var contextAttributes: MutableMap<String, Any> = mutableMapOf()
  825. val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name)
  826. val username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME)
  827. val password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD)
  828. if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
  829. contextAttributes = hashMapOf()
  830. // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
  831. contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username
  832. contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password
  833. }
  834. contextAttributes
  835. }
  836. }
  837. ----
  838. ======
  839. Given the preceding properties and bean, you can obtain the `OAuth2AccessToken` as follows:
  840. [tabs]
  841. ======
  842. Java::
  843. +
  844. [source,java,role="primary"]
  845. ----
  846. @Controller
  847. public class OAuth2ClientController {
  848. @Autowired
  849. private OAuth2AuthorizedClientManager authorizedClientManager;
  850. @GetMapping("/")
  851. public String index(Authentication authentication,
  852. HttpServletRequest servletRequest,
  853. HttpServletResponse servletResponse) {
  854. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  855. .principal(authentication)
  856. .attributes(attrs -> {
  857. attrs.put(HttpServletRequest.class.getName(), servletRequest);
  858. attrs.put(HttpServletResponse.class.getName(), servletResponse);
  859. })
  860. .build();
  861. OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
  862. OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
  863. // ...
  864. return "index";
  865. }
  866. }
  867. ----
  868. Kotlin::
  869. +
  870. [source,kotlin,role="secondary"]
  871. ----
  872. @Controller
  873. class OAuth2ClientController {
  874. @Autowired
  875. private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
  876. @GetMapping("/")
  877. fun index(authentication: Authentication?,
  878. servletRequest: HttpServletRequest,
  879. servletResponse: HttpServletResponse): String {
  880. val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  881. .principal(authentication)
  882. .attributes(Consumer {
  883. it[HttpServletRequest::class.java.name] = servletRequest
  884. it[HttpServletResponse::class.java.name] = servletResponse
  885. })
  886. .build()
  887. val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
  888. val accessToken: OAuth2AccessToken = authorizedClient.accessToken
  889. // ...
  890. return "index"
  891. }
  892. }
  893. ----
  894. ======
  895. [NOTE]
  896. ====
  897. `HttpServletRequest` and `HttpServletResponse` are both OPTIONAL attributes.
  898. If not provided, they default to `ServletRequestAttributes` using `RequestContextHolder.getRequestAttributes()`.
  899. ====
  900. [[oauth2-client-jwt-bearer]]
  901. == [[oauth2Client-jwt-bearer-grant]]JWT Bearer
  902. [NOTE]
  903. ====
  904. 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.
  905. ====
  906. [[oauth2-client-jwt-bearer-access-token]]
  907. === Requesting an Access Token
  908. [NOTE]
  909. ====
  910. 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.
  911. ====
  912. There are two implementations of `OAuth2AccessTokenResponseClient` that can be used to make HTTP requests to the Token Endpoint in order to obtain an access token for the JWT Bearer grant:
  913. * `DefaultJwtBearerTokenResponseClient` (_default_)
  914. * `RestClientJwtBearerTokenResponseClient`
  915. The default implementation uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint.
  916. Spring Security 6.4 introduces a new implementation based on `RestClient`, which provides similar functionality but is better aligned with the Reactive version of the component (based on `WebClient`) in order to provide consistent configuration for applications on either stack.
  917. [NOTE]
  918. ====
  919. This section focuses on `RestClientJwtBearerTokenResponseClient`.
  920. You can read about {spring-security-reference-base-url}/6.3/servlet/oauth2/client/authorization-grants.html#_requesting_an_access_token_4[`DefaultClientCredentialsTokenResponseClient`] in the Spring Security 6.3 documentation.
  921. ====
  922. :section-id: jwt-bearer
  923. :grant-type: JWT Bearer
  924. :class-name: RestClientJwtBearerTokenResponseClient
  925. :grant-request: JwtBearerGrantRequest
  926. :leveloffset: +1
  927. include::partial$servlet/oauth2/client/rest-client-access-token-response-client.adoc[]
  928. :leveloffset: -1
  929. [[oauth2-client-jwt-bearer-authorized-client-provider-builder]]
  930. === Customize using the Builder
  931. Whether you customize `RestClientJwtBearerTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you can configure it using the `OAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-jwt-bearer-access-token-response-client-bean,publishing a bean>>) as follows:
  932. .Access Token Response Configuration via Builder
  933. [tabs]
  934. ======
  935. Java::
  936. +
  937. [source,java,role="primary"]
  938. ----
  939. // Customize
  940. OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient = ...
  941. JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider();
  942. jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);
  943. OAuth2AuthorizedClientProvider authorizedClientProvider =
  944. OAuth2AuthorizedClientProviderBuilder.builder()
  945. .provider(jwtBearerAuthorizedClientProvider)
  946. .build();
  947. // ...
  948. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  949. ----
  950. Kotlin::
  951. +
  952. [source,kotlin,role="secondary"]
  953. ----
  954. // Customize
  955. val jwtBearerTokenResponseClient: OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> = ...
  956. val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
  957. jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient)
  958. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  959. .provider(jwtBearerAuthorizedClientProvider)
  960. .build()
  961. // ...
  962. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  963. ----
  964. ======
  965. [[oauth2-client-jwt-bearer-authorized-client-manager]]
  966. === Using the Access Token
  967. Given the following Spring Boot properties for an OAuth 2.0 Client registration:
  968. [source,yaml]
  969. ----
  970. spring:
  971. security:
  972. oauth2:
  973. client:
  974. registration:
  975. okta:
  976. client-id: okta-client-id
  977. client-secret: okta-client-secret
  978. authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer
  979. scope: read
  980. provider:
  981. okta:
  982. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  983. ----
  984. ...and the `OAuth2AuthorizedClientManager` `@Bean`:
  985. [tabs]
  986. ======
  987. Java::
  988. +
  989. [source,java,role="primary"]
  990. ----
  991. @Bean
  992. public OAuth2AuthorizedClientManager authorizedClientManager(
  993. ClientRegistrationRepository clientRegistrationRepository,
  994. OAuth2AuthorizedClientRepository authorizedClientRepository) {
  995. JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider =
  996. new JwtBearerOAuth2AuthorizedClientProvider();
  997. OAuth2AuthorizedClientProvider authorizedClientProvider =
  998. OAuth2AuthorizedClientProviderBuilder.builder()
  999. .provider(jwtBearerAuthorizedClientProvider)
  1000. .build();
  1001. DefaultOAuth2AuthorizedClientManager authorizedClientManager =
  1002. new DefaultOAuth2AuthorizedClientManager(
  1003. clientRegistrationRepository, authorizedClientRepository);
  1004. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  1005. return authorizedClientManager;
  1006. }
  1007. ----
  1008. Kotlin::
  1009. +
  1010. [source,kotlin,role="secondary"]
  1011. ----
  1012. @Bean
  1013. fun authorizedClientManager(
  1014. clientRegistrationRepository: ClientRegistrationRepository,
  1015. authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
  1016. val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
  1017. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  1018. .provider(jwtBearerAuthorizedClientProvider)
  1019. .build()
  1020. val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
  1021. clientRegistrationRepository, authorizedClientRepository)
  1022. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  1023. return authorizedClientManager
  1024. }
  1025. ----
  1026. ======
  1027. You may obtain the `OAuth2AccessToken` as follows:
  1028. [tabs]
  1029. ======
  1030. Java::
  1031. +
  1032. [source,java,role="primary"]
  1033. ----
  1034. @RestController
  1035. public class OAuth2ResourceServerController {
  1036. @Autowired
  1037. private OAuth2AuthorizedClientManager authorizedClientManager;
  1038. @GetMapping("/resource")
  1039. public String resource(JwtAuthenticationToken jwtAuthentication) {
  1040. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  1041. .principal(jwtAuthentication)
  1042. .build();
  1043. OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
  1044. OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
  1045. // ...
  1046. }
  1047. }
  1048. ----
  1049. Kotlin::
  1050. +
  1051. [source,kotlin,role="secondary"]
  1052. ----
  1053. class OAuth2ResourceServerController {
  1054. @Autowired
  1055. private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
  1056. @GetMapping("/resource")
  1057. fun resource(jwtAuthentication: JwtAuthenticationToken?): String {
  1058. val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  1059. .principal(jwtAuthentication)
  1060. .build()
  1061. val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
  1062. val accessToken: OAuth2AccessToken = authorizedClient.accessToken
  1063. // ...
  1064. }
  1065. }
  1066. ----
  1067. ======
  1068. [NOTE]
  1069. ====
  1070. `JwtBearerOAuth2AuthorizedClientProvider` resolves the `Jwt` assertion via `OAuth2AuthorizationContext.getPrincipal().getPrincipal()` by default, hence the use of `JwtAuthenticationToken` in the preceding example.
  1071. ====
  1072. [TIP]
  1073. ====
  1074. If you need to resolve the `Jwt` assertion from a different source, you can provide `JwtBearerOAuth2AuthorizedClientProvider.setJwtAssertionResolver()` with a custom `Function<OAuth2AuthorizationContext, Jwt>`.
  1075. ====
  1076. [[oauth2-client-token-exchange]]
  1077. == [[oauth2Client-token-exchange-grant]]Token Exchange
  1078. [NOTE]
  1079. ====
  1080. Please refer to OAuth 2.0 Token Exchange for further details on the https://datatracker.ietf.org/doc/html/rfc8693[Token Exchange] grant.
  1081. ====
  1082. [[oauth2-client-token-exchange-access-token]]
  1083. === Requesting an Access Token
  1084. [NOTE]
  1085. ====
  1086. 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.
  1087. ====
  1088. There are two implementations of `OAuth2AccessTokenResponseClient` that can be used to make HTTP requests to the Token Endpoint in order to obtain an access token for the Token Exchange grant:
  1089. * `DefaultTokenExchangeTokenResponseClient` (_default_)
  1090. * `RestClientTokenExchangeTokenResponseClient`
  1091. The default implementation uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint.
  1092. Spring Security 6.4 introduces a new implementation based on `RestClient`, which provides similar functionality but is better aligned with the Reactive version of the component (based on `WebClient`) in order to provide consistent configuration for applications on either stack.
  1093. [NOTE]
  1094. ====
  1095. This section focuses on `RestClientTokenExchangeTokenResponseClient`.
  1096. You can read about {spring-security-reference-base-url}/6.3/servlet/oauth2/client/authorization-grants.html#_requesting_an_access_token_5[`DefaultTokenExchangeTokenResponseClient`] in the Spring Security 6.3 documentation.
  1097. ====
  1098. :section-id: token-exchange
  1099. :grant-type: Token Exchange
  1100. :class-name: RestClientTokenExchangeTokenResponseClient
  1101. :grant-request: TokenExchangeGrantRequest
  1102. :leveloffset: +1
  1103. include::partial$servlet/oauth2/client/rest-client-access-token-response-client.adoc[]
  1104. :leveloffset: -1
  1105. [[oauth2-client-token-exchange-authorized-client-provider-builder]]
  1106. === Customize using the Builder
  1107. Whether you customize `RestClientTokenExchangeTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you can configure it using the `OAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-token-exchange-access-token-response-client-bean,publishing a bean>>) as follows:
  1108. .Access Token Response Configuration via Builder
  1109. [tabs]
  1110. ======
  1111. Java::
  1112. +
  1113. [source,java,role="primary"]
  1114. ----
  1115. // Customize
  1116. OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> tokenExchangeTokenResponseClient = ...
  1117. TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider = new TokenExchangeOAuth2AuthorizedClientProvider();
  1118. tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient);
  1119. OAuth2AuthorizedClientProvider authorizedClientProvider =
  1120. OAuth2AuthorizedClientProviderBuilder.builder()
  1121. .provider(tokenExchangeAuthorizedClientProvider)
  1122. .build();
  1123. // ...
  1124. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  1125. ----
  1126. Kotlin::
  1127. +
  1128. [source,kotlin,role="secondary"]
  1129. ----
  1130. // Customize
  1131. val tokenExchangeTokenResponseClient: OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> = ...
  1132. val tokenExchangeAuthorizedClientProvider = TokenExchangeOAuth2AuthorizedClientProvider()
  1133. tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient)
  1134. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  1135. .provider(tokenExchangeAuthorizedClientProvider)
  1136. .build()
  1137. // ...
  1138. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  1139. ----
  1140. ======
  1141. [[oauth2-client-token-exchange-authorized-client-manager]]
  1142. === [[token-exchange-grant-access-token]]Using the Access Token
  1143. Given the following Spring Boot properties for an OAuth 2.0 Client registration:
  1144. [source,yaml]
  1145. ----
  1146. spring:
  1147. security:
  1148. oauth2:
  1149. client:
  1150. registration:
  1151. okta:
  1152. client-id: okta-client-id
  1153. client-secret: okta-client-secret
  1154. authorization-grant-type: urn:ietf:params:oauth:grant-type:token-exchange
  1155. scope: read
  1156. provider:
  1157. okta:
  1158. token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
  1159. ----
  1160. ...and the `OAuth2AuthorizedClientManager` `@Bean`:
  1161. [tabs]
  1162. ======
  1163. Java::
  1164. +
  1165. [source,java,role="primary"]
  1166. ----
  1167. @Bean
  1168. public OAuth2AuthorizedClientManager authorizedClientManager(
  1169. ClientRegistrationRepository clientRegistrationRepository,
  1170. OAuth2AuthorizedClientRepository authorizedClientRepository) {
  1171. TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider =
  1172. new TokenExchangeOAuth2AuthorizedClientProvider();
  1173. OAuth2AuthorizedClientProvider authorizedClientProvider =
  1174. OAuth2AuthorizedClientProviderBuilder.builder()
  1175. .provider(tokenExchangeAuthorizedClientProvider)
  1176. .build();
  1177. DefaultOAuth2AuthorizedClientManager authorizedClientManager =
  1178. new DefaultOAuth2AuthorizedClientManager(
  1179. clientRegistrationRepository, authorizedClientRepository);
  1180. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  1181. return authorizedClientManager;
  1182. }
  1183. ----
  1184. Kotlin::
  1185. +
  1186. [source,kotlin,role="secondary"]
  1187. ----
  1188. @Bean
  1189. fun authorizedClientManager(
  1190. clientRegistrationRepository: ClientRegistrationRepository,
  1191. authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
  1192. val tokenExchangeAuthorizedClientProvider = TokenExchangeOAuth2AuthorizedClientProvider()
  1193. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  1194. .provider(tokenExchangeAuthorizedClientProvider)
  1195. .build()
  1196. val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
  1197. clientRegistrationRepository, authorizedClientRepository)
  1198. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  1199. return authorizedClientManager
  1200. }
  1201. ----
  1202. ======
  1203. You may obtain the `OAuth2AccessToken` as follows:
  1204. [tabs]
  1205. ======
  1206. Java::
  1207. +
  1208. [source,java,role="primary"]
  1209. ----
  1210. @RestController
  1211. public class OAuth2ResourceServerController {
  1212. @Autowired
  1213. private OAuth2AuthorizedClientManager authorizedClientManager;
  1214. @GetMapping("/resource")
  1215. public String resource(JwtAuthenticationToken jwtAuthentication) {
  1216. OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  1217. .principal(jwtAuthentication)
  1218. .build();
  1219. OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
  1220. OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
  1221. // ...
  1222. }
  1223. }
  1224. ----
  1225. Kotlin::
  1226. +
  1227. [source,kotlin,role="secondary"]
  1228. ----
  1229. class OAuth2ResourceServerController {
  1230. @Autowired
  1231. private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
  1232. @GetMapping("/resource")
  1233. fun resource(jwtAuthentication: JwtAuthenticationToken?): String {
  1234. val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
  1235. .principal(jwtAuthentication)
  1236. .build()
  1237. val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
  1238. val accessToken: OAuth2AccessToken = authorizedClient.accessToken
  1239. // ...
  1240. }
  1241. }
  1242. ----
  1243. ======
  1244. [NOTE]
  1245. ====
  1246. `TokenExchangeOAuth2AuthorizedClientProvider` resolves the subject token (as an `OAuth2Token`) via `OAuth2AuthorizationContext.getPrincipal().getPrincipal()` by default, hence the use of `JwtAuthenticationToken` in the preceding example.
  1247. An actor token is not resolved by default.
  1248. ====
  1249. [TIP]
  1250. ====
  1251. If you need to resolve the subject token from a different source, you can provide `TokenExchangeOAuth2AuthorizedClientProvider.setSubjectTokenResolver()` with a custom `Function<OAuth2AuthorizationContext, OAuth2Token>`.
  1252. ====
  1253. [TIP]
  1254. ====
  1255. If you need to resolve an actor token, you can provide `TokenExchangeOAuth2AuthorizedClientProvider.setActorTokenResolver()` with a custom `Function<OAuth2AuthorizationContext, OAuth2Token>`.
  1256. ====