index.adoc 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017
  1. = OAuth2
  2. Spring Security provides comprehensive OAuth 2.0 support.
  3. This section discusses how to integrate OAuth 2.0 into your servlet based application.
  4. [[oauth2-overview]]
  5. == Overview
  6. Spring Security's OAuth 2.0 support consists of two primary feature sets:
  7. * <<oauth2-resource-server>>
  8. * <<oauth2-client>>
  9. [NOTE]
  10. ====
  11. <<oauth2-client-log-users-in,OAuth2 Login>> is a very powerful OAuth2 Client feature that deserves its own section in the reference documentation.
  12. However, it does not exist as a standalone feature and requires OAuth2 Client in order to function.
  13. ====
  14. These feature sets cover the _resource server_ and _client_ roles defined in the https://tools.ietf.org/html/rfc6749#section-1.1[OAuth 2.0 Authorization Framework], while the _authorization server_ role is covered by https://docs.spring.io/spring-authorization-server/reference/index.html[Spring Authorization Server], which is a separate project built on xref:index.adoc[Spring Security].
  15. The _resource server_ and _client_ roles in OAuth2 are typically represented by one or more server-side applications.
  16. Additionally, the _authorization server_ role can be represented by one or more third parties (as is the case when centralizing identity management and/or authentication within an organization) *-or-* it can be represented by an application (as is the case with Spring Authorization Server).
  17. For example, a typical OAuth2-based microservices architecture might consist of a single user-facing client application, several backend resource servers providing REST APIs and a third party authorization server for managing users and authentication concerns.
  18. It is also common to have a single application representing only one of these roles with the need to integrate with one or more third parties that are providing the other roles.
  19. Spring Security handles these scenarios and more.
  20. The following sections cover the roles provided by Spring Security and contain examples for common scenarios.
  21. [[oauth2-resource-server]]
  22. == OAuth2 Resource Server
  23. [NOTE]
  24. ====
  25. This section contains a summary of OAuth2 Resource Server features with examples.
  26. See xref:servlet/oauth2/resource-server/index.adoc[OAuth 2.0 Resource Server] for complete reference documentation.
  27. ====
  28. To get started, add the `spring-security-oauth2-resource-server` dependency to your project.
  29. When using Spring Boot, add the following starter:
  30. .OAuth2 Client with Spring Boot
  31. [tabs]
  32. ======
  33. Gradle::
  34. +
  35. [source,gradle,role="primary"]
  36. ----
  37. implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
  38. ----
  39. Maven::
  40. +
  41. [source,maven,role="secondary"]
  42. ----
  43. <dependency>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
  46. </dependency>
  47. ----
  48. ======
  49. [TIP]
  50. ====
  51. See xref:getting-spring-security.adoc[] for additional options when not using Spring Boot.
  52. ====
  53. Consider the following use cases for OAuth2 Resource Server:
  54. * I want to <<oauth2-resource-server-access-token,protect access to the API using OAuth2>> (authorization server provides JWT or opaque access token)
  55. * I want to <<oauth2-resource-server-custom-jwt,protect access to the API using a JWT>> (custom token)
  56. [[oauth2-resource-server-access-token]]
  57. === Protect Access with an OAuth2 Access Token
  58. It is very common to protect access to an API using OAuth2 access tokens.
  59. In most cases, Spring Security requires only minimal configuration to secure an application with OAuth2.
  60. There are two types of `Bearer` tokens supported by Spring Security which each use a different component for validation:
  61. * <<oauth2-resource-server-access-token-jwt,JWT support>> uses a `JwtDecoder` bean to validate signatures and decode tokens
  62. * <<oauth2-resource-server-access-token-opaque,Opaque token support>> uses an `OpaqueTokenIntrospector` bean to introspect tokens
  63. [[oauth2-resource-server-access-token-jwt]]
  64. ==== JWT Support
  65. The following example configures a `JwtDecoder` bean using Spring Boot configuration properties:
  66. [source,yaml]
  67. ----
  68. spring:
  69. security:
  70. oauth2:
  71. resourceserver:
  72. jwt:
  73. issuer-uri: https://my-auth-server.com
  74. ----
  75. When using Spring Boot, this is all that is required.
  76. The default arrangement provided by Spring Boot is equivalent to the following:
  77. .Configure Resource Server with JWTs
  78. [tabs]
  79. =====
  80. Java::
  81. +
  82. [source,java,role="primary"]
  83. ----
  84. @Configuration
  85. @EnableWebSecurity
  86. public class SecurityConfig {
  87. @Bean
  88. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  89. http
  90. .authorizeHttpRequests((authorize) -> authorize
  91. .anyRequest().authenticated()
  92. )
  93. .oauth2ResourceServer((oauth2) -> oauth2
  94. .jwt(Customizer.withDefaults())
  95. );
  96. return http.build();
  97. }
  98. @Bean
  99. public JwtDecoder jwtDecoder() {
  100. return JwtDecoders.fromIssuerLocation("https://my-auth-server.com");
  101. }
  102. }
  103. ----
  104. Kotlin::
  105. +
  106. [source,kotlin,role="secondary"]
  107. ----
  108. import org.springframework.security.config.annotation.web.invoke
  109. @Configuration
  110. @EnableWebSecurity
  111. class SecurityConfig {
  112. @Bean
  113. fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  114. http {
  115. authorizeHttpRequests {
  116. authorize(anyRequest, authenticated)
  117. }
  118. oauth2ResourceServer {
  119. jwt { }
  120. }
  121. }
  122. return http.build()
  123. }
  124. @Bean
  125. fun jwtDecoder(): JwtDecoder {
  126. return JwtDecoders.fromIssuerLocation("https://my-auth-server.com")
  127. }
  128. }
  129. ----
  130. =====
  131. [[oauth2-resource-server-access-token-opaque]]
  132. ==== Opaque Token Support
  133. The following example configures an `OpaqueTokenIntrospector` bean using Spring Boot configuration properties:
  134. [source,yaml]
  135. ----
  136. spring:
  137. security:
  138. oauth2:
  139. resourceserver:
  140. opaquetoken:
  141. introspection-uri: https://my-auth-server.com/oauth2/introspect
  142. client-id: my-client-id
  143. client-secret: my-client-secret
  144. ----
  145. When using Spring Boot, this is all that is required.
  146. The default arrangement provided by Spring Boot is equivalent to the following:
  147. .Configure Resource Server with Opaque Tokens
  148. [tabs]
  149. =====
  150. Java::
  151. +
  152. [source,java,role="primary"]
  153. ----
  154. @Configuration
  155. @EnableWebSecurity
  156. public class SecurityConfig {
  157. @Bean
  158. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  159. http
  160. .authorizeHttpRequests((authorize) -> authorize
  161. .anyRequest().authenticated()
  162. )
  163. .oauth2ResourceServer((oauth2) -> oauth2
  164. .opaqueToken(Customizer.withDefaults())
  165. );
  166. return http.build();
  167. }
  168. @Bean
  169. public OpaqueTokenIntrospector opaqueTokenIntrospector() {
  170. return new SpringOpaqueTokenIntrospector(
  171. "https://my-auth-server.com/oauth2/introspect", "my-client-id", "my-client-secret");
  172. }
  173. }
  174. ----
  175. Kotlin::
  176. +
  177. [source,kotlin,role="secondary"]
  178. ----
  179. import org.springframework.security.config.annotation.web.invoke
  180. @Configuration
  181. @EnableWebSecurity
  182. class SecurityConfig {
  183. @Bean
  184. fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  185. http {
  186. authorizeHttpRequests {
  187. authorize(anyRequest, authenticated)
  188. }
  189. oauth2ResourceServer {
  190. opaqueToken { }
  191. }
  192. }
  193. return http.build()
  194. }
  195. @Bean
  196. fun opaqueTokenIntrospector(): OpaqueTokenIntrospector {
  197. return SpringOpaqueTokenIntrospector(
  198. "https://my-auth-server.com/oauth2/introspect", "my-client-id", "my-client-secret"
  199. )
  200. }
  201. }
  202. ----
  203. =====
  204. [[oauth2-resource-server-custom-jwt]]
  205. === Protect Access with a custom JWT
  206. It is a fairly common goal to protect access to an API using JWTs, particularly when the frontend is developed as a single-page application.
  207. The OAuth2 Resource Server support in Spring Security can be used for any type of `Bearer` token, including a custom JWT.
  208. All that is required to protect an API using JWTs is a `JwtDecoder` bean, which is used to validate signatures and decode tokens.
  209. Spring Security will automatically use the provided bean to configure protection within the `SecurityFilterChain`.
  210. The following example configures a `JwtDecoder` bean using Spring Boot configuration properties:
  211. [source,yaml]
  212. ----
  213. spring:
  214. security:
  215. oauth2:
  216. resourceserver:
  217. jwt:
  218. public-key-location: classpath:my-public-key.pub
  219. ----
  220. [NOTE]
  221. ====
  222. You can provide the public key as a classpath resource (called `my-public-key.pub` in this example).
  223. ====
  224. When using Spring Boot, this is all that is required.
  225. The default arrangement provided by Spring Boot is equivalent to the following:
  226. .Configure Resource Server with Custom JWTs
  227. [tabs]
  228. =====
  229. Java::
  230. +
  231. [source,java,role="primary"]
  232. ----
  233. @Configuration
  234. @EnableWebSecurity
  235. public class SecurityConfig {
  236. @Bean
  237. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  238. http
  239. .authorizeHttpRequests((authorize) -> authorize
  240. .anyRequest().authenticated()
  241. )
  242. .oauth2ResourceServer((oauth2) -> oauth2
  243. .jwt(Customizer.withDefaults())
  244. );
  245. return http.build();
  246. }
  247. @Bean
  248. public JwtDecoder jwtDecoder() {
  249. return NimbusJwtDecoder.withPublicKey(publicKey()).build();
  250. }
  251. private RSAPublicKey publicKey() {
  252. // ...
  253. }
  254. }
  255. ----
  256. Kotlin::
  257. +
  258. [source,kotlin,role="secondary"]
  259. ----
  260. import org.springframework.security.config.annotation.web.invoke
  261. @Configuration
  262. @EnableWebSecurity
  263. class SecurityConfig {
  264. @Bean
  265. fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  266. http {
  267. authorizeHttpRequests {
  268. authorize(anyRequest, authenticated)
  269. }
  270. oauth2ResourceServer {
  271. jwt { }
  272. }
  273. }
  274. return http.build()
  275. }
  276. @Bean
  277. fun jwtDecoder(): JwtDecoder {
  278. return NimbusJwtDecoder.withPublicKey(publicKey()).build()
  279. }
  280. private fun publicKey(): RSAPublicKey {
  281. // ...
  282. }
  283. }
  284. ----
  285. =====
  286. [NOTE]
  287. ====
  288. Spring Security does not provide an endpoint for minting tokens.
  289. However, Spring Security does provide the `JwtEncoder` interface along with one implementation, which is `NimbusJwtEncoder`.
  290. ====
  291. [[oauth2-client]]
  292. == OAuth2 Client
  293. [NOTE]
  294. ====
  295. This section contains a summary of OAuth2 Client features with examples.
  296. See xref:servlet/oauth2/client/index.adoc[OAuth 2.0 Client] and xref:servlet/oauth2/login/index.adoc[OAuth 2.0 Login] for complete reference documentation.
  297. ====
  298. To get started, add the `spring-security-oauth2-client` dependency to your project.
  299. When using Spring Boot, add the following starter:
  300. .OAuth2 Client with Spring Boot
  301. [tabs]
  302. ======
  303. Gradle::
  304. +
  305. [source,gradle,role="primary"]
  306. ----
  307. implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
  308. ----
  309. Maven::
  310. +
  311. [source,maven,role="secondary"]
  312. ----
  313. <dependency>
  314. <groupId>org.springframework.boot</groupId>
  315. <artifactId>spring-boot-starter-oauth2-client</artifactId>
  316. </dependency>
  317. ----
  318. ======
  319. [TIP]
  320. ====
  321. See xref:getting-spring-security.adoc[] for additional options when not using Spring Boot.
  322. ====
  323. Consider the following use cases for OAuth2 Client:
  324. * I want to <<oauth2-client-log-users-in,log users in using OAuth 2.0 or OpenID Connect 1.0>>
  325. * I want to <<oauth2-client-access-protected-resources,use `RestClient` to obtain an access token for users>> in order to access a third-party API
  326. * I want to <<oauth2-client-access-protected-resources-webclient,use `WebClient` to obtain an access token for users>> in order to access a third-party API
  327. * I want to <<oauth2-client-access-protected-resources-current-user,do both>> (log users in _and_ access a third-party API)
  328. * I want to <<oauth2-client-client-credentials,use the `client_credentials` grant type>> to obtain a single token per application
  329. * I want to <<oauth2-client-enable-extension-grant-type,enable an extension grant type>>
  330. * I want to <<oauth2-client-customize-existing-grant-type,customize an existing grant type>>
  331. * I want to <<oauth2-client-customize-request-parameters,customize token request parameters>>
  332. * I want to <<oauth2-client-customize-rest-client,customize the `RestClient` used by OAuth2 Client components>>
  333. [[oauth2-client-log-users-in]]
  334. === Log Users In with OAuth2
  335. It is very common to require users to log in via OAuth2.
  336. https://openid.net/specs/openid-connect-core-1_0.html[OpenID Connect 1.0] provides a special token called the `id_token` which is designed to provide an OAuth2 Client with the ability to perform user identity verification and log users in.
  337. In certain cases, OAuth2 can be used directly to log users in (as is the case with popular social login providers that do not implement OpenID Connect such as GitHub and Facebook).
  338. The following example configures the application to act as an OAuth2 Client capable of logging users in with OAuth2 or OpenID Connect:
  339. .Configure OAuth2 Login
  340. [tabs]
  341. =====
  342. Java::
  343. +
  344. [source,java,role="primary"]
  345. ----
  346. @Configuration
  347. @EnableWebSecurity
  348. public class SecurityConfig {
  349. @Bean
  350. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  351. http
  352. // ...
  353. .oauth2Login(Customizer.withDefaults());
  354. return http.build();
  355. }
  356. }
  357. ----
  358. Kotlin::
  359. +
  360. [source,kotlin,role="secondary"]
  361. ----
  362. import org.springframework.security.config.annotation.web.invoke
  363. @Configuration
  364. @EnableWebSecurity
  365. class SecurityConfig {
  366. @Bean
  367. fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  368. http {
  369. // ...
  370. oauth2Login { }
  371. }
  372. return http.build()
  373. }
  374. }
  375. ----
  376. =====
  377. In addition to the above configuration, the application requires at least one `ClientRegistration` to be configured through the use of a `ClientRegistrationRepository` bean.
  378. The following example configures an `InMemoryClientRegistrationRepository` bean using Spring Boot configuration properties:
  379. [source,yaml]
  380. ----
  381. spring:
  382. security:
  383. oauth2:
  384. client:
  385. registration:
  386. my-oidc-client:
  387. provider: my-oidc-provider
  388. client-id: my-client-id
  389. client-secret: my-client-secret
  390. authorization-grant-type: authorization_code
  391. scope: openid,profile
  392. provider:
  393. my-oidc-provider:
  394. issuer-uri: https://my-oidc-provider.com
  395. ----
  396. With the above configuration, the application now supports two additional endpoints:
  397. 1. The login endpoint (e.g. `/oauth2/authorization/my-oidc-client`) is used to initiate login and perform a redirect to the third party authorization server.
  398. 2. The redirection endpoint (e.g. `/login/oauth2/code/my-oidc-client`) is used by the authorization server to redirect back to the client application, and will contain a `code` parameter used to obtain an `id_token` and/or `access_token` via the access token request.
  399. [NOTE]
  400. ====
  401. The presence of the `openid` scope in the above configuration indicates that OpenID Connect 1.0 should be used.
  402. This instructs Spring Security to use OIDC-specific components (such as `OidcUserService`) during request processing.
  403. Without this scope, Spring Security will use OAuth2-specific components (such as `DefaultOAuth2UserService`) instead.
  404. ====
  405. [[oauth2-client-access-protected-resources]]
  406. === Access Protected Resources
  407. Making requests to a third party API that is protected by OAuth2 is a core use case of OAuth2 Client.
  408. This is accomplished by authorizing a client (represented by the `OAuth2AuthorizedClient` class in Spring Security) and accessing protected resources by placing a `Bearer` token in the `Authorization` header of an outbound request.
  409. The following example configures the application to act as an OAuth2 Client capable of requesting protected resources from a third party API:
  410. .Configure OAuth2 Client
  411. [tabs]
  412. =====
  413. Java::
  414. +
  415. [source,java,role="primary"]
  416. ----
  417. @Configuration
  418. @EnableWebSecurity
  419. public class SecurityConfig {
  420. @Bean
  421. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  422. http
  423. // ...
  424. .oauth2Client(Customizer.withDefaults());
  425. return http.build();
  426. }
  427. }
  428. ----
  429. Kotlin::
  430. +
  431. [source,kotlin,role="secondary"]
  432. ----
  433. import org.springframework.security.config.annotation.web.invoke
  434. @Configuration
  435. @EnableWebSecurity
  436. class SecurityConfig {
  437. @Bean
  438. fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  439. http {
  440. // ...
  441. oauth2Client { }
  442. }
  443. return http.build()
  444. }
  445. }
  446. ----
  447. =====
  448. [NOTE]
  449. ====
  450. The above example does not provide a way to log users in.
  451. You can use any other login mechanism (such as `formLogin()`).
  452. See the <<oauth2-client-access-protected-resources-current-user,next section>> for an example combining `oauth2Client()` with `oauth2Login()`.
  453. ====
  454. In addition to the above configuration, the application requires at least one `ClientRegistration` to be configured through the use of a `ClientRegistrationRepository` bean.
  455. The following example configures an `InMemoryClientRegistrationRepository` bean using Spring Boot configuration properties:
  456. [source,yaml]
  457. ----
  458. spring:
  459. security:
  460. oauth2:
  461. client:
  462. registration:
  463. my-oauth2-client:
  464. provider: my-auth-server
  465. client-id: my-client-id
  466. client-secret: my-client-secret
  467. authorization-grant-type: authorization_code
  468. scope: message.read,message.write
  469. provider:
  470. my-auth-server:
  471. issuer-uri: https://my-auth-server.com
  472. ----
  473. In addition to configuring Spring Security to support OAuth2 Client features, you will also need to decide how you will be accessing protected resources and configure your application accordingly.
  474. Spring Security provides implementations of `OAuth2AuthorizedClientManager` for obtaining access tokens that can be used to access protected resources.
  475. [TIP]
  476. ====
  477. Spring Security registers a default `OAuth2AuthorizedClientManager` bean for you when one does not exist.
  478. ====
  479. The easiest way to use an `OAuth2AuthorizedClientManager` is via a `ClientHttpRequestInterceptor` that intercepts requests through a `RestClient`, which is already available when `spring-web` is on the classpath.
  480. The following example uses the default `OAuth2AuthorizedClientManager` to configure a `RestClient` capable of accessing protected resources by placing `Bearer` tokens in the `Authorization` header of each request:
  481. .Configure `RestClient` with `ClientHttpRequestInterceptor`
  482. [tabs]
  483. =====
  484. Java::
  485. +
  486. [source,java,role="primary"]
  487. ----
  488. @Configuration
  489. public class RestClientConfig {
  490. @Bean
  491. public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  492. OAuth2ClientHttpRequestInterceptor requestInterceptor =
  493. new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
  494. return RestClient.builder()
  495. .requestInterceptor(requestInterceptor)
  496. .build();
  497. }
  498. }
  499. ----
  500. Kotlin::
  501. +
  502. [source,kotlin,role="secondary"]
  503. ----
  504. @Configuration
  505. class RestClientConfig {
  506. @Bean
  507. fun restClient(authorizedClientManager: OAuth2AuthorizedClientManager): RestClient {
  508. val requestInterceptor = OAuth2ClientHttpRequestInterceptor(authorizedClientManager)
  509. return RestClient.builder()
  510. .requestInterceptor(requestInterceptor)
  511. .build()
  512. }
  513. }
  514. ----
  515. =====
  516. This configured `RestClient` can be used as in the following example:
  517. [[oauth2-client-accessing-protected-resources-example]]
  518. .Use `RestClient` to Access Protected Resources
  519. [tabs]
  520. =====
  521. Java::
  522. +
  523. [source,java,role="primary"]
  524. ----
  525. import static org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver.clientRegistrationId;
  526. @RestController
  527. public class MessagesController {
  528. private final RestClient restClient;
  529. public MessagesController(RestClient restClient) {
  530. this.restClient = restClient;
  531. }
  532. @GetMapping("/messages")
  533. public ResponseEntity<List<Message>> messages() {
  534. Message[] messages = this.restClient.get()
  535. .uri("http://localhost:8090/messages")
  536. .attributes(clientRegistrationId("my-oauth2-client"))
  537. .retrieve()
  538. .body(Message[].class);
  539. return ResponseEntity.ok(Arrays.asList(messages));
  540. }
  541. public record Message(String message) {
  542. }
  543. }
  544. ----
  545. Kotlin::
  546. +
  547. [source,kotlin,role="secondary"]
  548. ----
  549. import org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver.clientRegistrationId
  550. import org.springframework.web.client.body
  551. @RestController
  552. class MessagesController(private val restClient: RestClient) {
  553. @GetMapping("/messages")
  554. fun messages(): ResponseEntity<List<Message>> {
  555. val messages = restClient.get()
  556. .uri("http://localhost:8090/messages")
  557. .attributes(clientRegistrationId("my-oauth2-client"))
  558. .retrieve()
  559. .body<Array<Message>>()!!
  560. .toList()
  561. return ResponseEntity.ok(messages)
  562. }
  563. data class Message(val message: String)
  564. }
  565. ----
  566. =====
  567. [[oauth2-client-access-protected-resources-webclient]]
  568. === Access Protected Resources with `WebClient`
  569. Making requests to a third party API that is protected by OAuth2 is a core use case of OAuth2 Client.
  570. This is accomplished by authorizing a client (represented by the `OAuth2AuthorizedClient` class in Spring Security) and accessing protected resources by placing a `Bearer` token in the `Authorization` header of an outbound request.
  571. The following example configures the application to act as an OAuth2 Client capable of requesting protected resources from a third party API:
  572. .Configure OAuth2 Client
  573. [tabs]
  574. =====
  575. Java::
  576. +
  577. [source,java,role="primary"]
  578. ----
  579. @Configuration
  580. @EnableWebSecurity
  581. public class SecurityConfig {
  582. @Bean
  583. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  584. http
  585. // ...
  586. .oauth2Client(Customizer.withDefaults());
  587. return http.build();
  588. }
  589. }
  590. ----
  591. Kotlin::
  592. +
  593. [source,kotlin,role="secondary"]
  594. ----
  595. import org.springframework.security.config.annotation.web.invoke
  596. @Configuration
  597. @EnableWebSecurity
  598. class SecurityConfig {
  599. @Bean
  600. fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  601. http {
  602. // ...
  603. oauth2Client { }
  604. }
  605. return http.build()
  606. }
  607. }
  608. ----
  609. =====
  610. [NOTE]
  611. ====
  612. The above example does not provide a way to log users in.
  613. You can use any other login mechanism (such as `formLogin()`).
  614. See the <<oauth2-client-access-protected-resources-current-user,previous section>> for an example combining `oauth2Client()` with `oauth2Login()`.
  615. ====
  616. In addition to the above configuration, the application requires at least one `ClientRegistration` to be configured through the use of a `ClientRegistrationRepository` bean.
  617. The following example configures an `InMemoryClientRegistrationRepository` bean using Spring Boot configuration properties:
  618. [source,yaml]
  619. ----
  620. spring:
  621. security:
  622. oauth2:
  623. client:
  624. registration:
  625. my-oauth2-client:
  626. provider: my-auth-server
  627. client-id: my-client-id
  628. client-secret: my-client-secret
  629. authorization-grant-type: authorization_code
  630. scope: message.read,message.write
  631. provider:
  632. my-auth-server:
  633. issuer-uri: https://my-auth-server.com
  634. ----
  635. In addition to configuring Spring Security to support OAuth2 Client features, you will also need to decide how you will be accessing protected resources and configure your application accordingly.
  636. Spring Security provides implementations of `OAuth2AuthorizedClientManager` for obtaining access tokens that can be used to access protected resources.
  637. [TIP]
  638. ====
  639. Spring Security registers a default `OAuth2AuthorizedClientManager` bean for you when one does not exist.
  640. ====
  641. <<oauth2-client-access-protected-resources,Instead of configuring a `RestClient`>>, another way to use an `OAuth2AuthorizedClientManager` is via an `ExchangeFilterFunction` that intercepts requests through a `WebClient`.
  642. To use `WebClient`, you will need to add the `spring-webflux` dependency along with a reactive client implementation:
  643. .Add Spring WebFlux Dependency
  644. [tabs]
  645. ======
  646. Gradle::
  647. +
  648. [source,gradle,role="primary"]
  649. ----
  650. implementation 'org.springframework:spring-webflux'
  651. implementation 'io.projectreactor.netty:reactor-netty'
  652. ----
  653. Maven::
  654. +
  655. [source,maven,role="secondary"]
  656. ----
  657. <dependency>
  658. <groupId>org.springframework</groupId>
  659. <artifactId>spring-webflux</artifactId>
  660. </dependency>
  661. <dependency>
  662. <groupId>io.projectreactor.netty</groupId>
  663. <artifactId>reactor-netty</artifactId>
  664. </dependency>
  665. ----
  666. ======
  667. The following example uses the default `OAuth2AuthorizedClientManager` to configure a `WebClient` capable of accessing protected resources by placing `Bearer` tokens in the `Authorization` header of each request:
  668. .Configure `WebClient` with `ExchangeFilterFunction`
  669. [tabs]
  670. =====
  671. Java::
  672. +
  673. [source,java,role="primary"]
  674. ----
  675. @Configuration
  676. public class WebClientConfig {
  677. @Bean
  678. public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  679. ServletOAuth2AuthorizedClientExchangeFilterFunction filter =
  680. new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
  681. return WebClient.builder()
  682. .apply(filter.oauth2Configuration())
  683. .build();
  684. }
  685. }
  686. ----
  687. Kotlin::
  688. +
  689. [source,kotlin,role="secondary"]
  690. ----
  691. @Configuration
  692. class WebClientConfig {
  693. @Bean
  694. fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager): WebClient {
  695. val filter = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager)
  696. return WebClient.builder()
  697. .apply(filter.oauth2Configuration())
  698. .build()
  699. }
  700. }
  701. ----
  702. =====
  703. This configured `WebClient` can be used as in the following example:
  704. .Use `WebClient` to Access Protected Resources
  705. [tabs]
  706. =====
  707. Java::
  708. +
  709. [source,java,role="primary"]
  710. ----
  711. import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId;
  712. @RestController
  713. public class MessagesController {
  714. private final WebClient webClient;
  715. public MessagesController(WebClient webClient) {
  716. this.webClient = webClient;
  717. }
  718. @GetMapping("/messages")
  719. public ResponseEntity<List<Message>> messages() {
  720. return this.webClient.get()
  721. .uri("http://localhost:8090/messages")
  722. .attributes(clientRegistrationId("my-oauth2-client"))
  723. .retrieve()
  724. .toEntityList(Message.class)
  725. .block();
  726. }
  727. public record Message(String message) {
  728. }
  729. }
  730. ----
  731. Kotlin::
  732. +
  733. [source,kotlin,role="secondary"]
  734. ----
  735. import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId
  736. @RestController
  737. class MessagesController(private val webClient: WebClient) {
  738. @GetMapping("/messages")
  739. fun messages(): ResponseEntity<List<Message>> {
  740. return webClient.get()
  741. .uri("http://localhost:8090/messages")
  742. .attributes(clientRegistrationId("my-oauth2-client"))
  743. .retrieve()
  744. .toEntityList<Message>()
  745. .block()!!
  746. }
  747. data class Message(val message: String)
  748. }
  749. ----
  750. =====
  751. [[oauth2-client-access-protected-resources-current-user]]
  752. === Access Protected Resources for the Current User
  753. When a user is logged in via OAuth2 or OpenID Connect, the authorization server may provide an access token that can be used directly to access protected resources.
  754. This is convenient because it only requires a single `ClientRegistration` to be configured for both use cases simultaneously.
  755. [NOTE]
  756. ====
  757. This section combines <<oauth2-client-log-users-in>> and <<oauth2-client-access-protected-resources>> into a single configuration.
  758. Other advanced scenarios exist, such as configuring one `ClientRegistration` for login and another for accessing protected resources.
  759. All such scenarios would use the same basic configuration.
  760. ====
  761. The following example configures the application to act as an OAuth2 Client capable of logging the user in _and_ requesting protected resources from a third party API:
  762. .Configure OAuth2 Login and OAuth2 Client
  763. [tabs]
  764. =====
  765. Java::
  766. +
  767. [source,java,role="primary"]
  768. ----
  769. @Configuration
  770. @EnableWebSecurity
  771. public class SecurityConfig {
  772. @Bean
  773. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  774. http
  775. // ...
  776. .oauth2Login(Customizer.withDefaults())
  777. .oauth2Client(Customizer.withDefaults());
  778. return http.build();
  779. }
  780. }
  781. ----
  782. Kotlin::
  783. +
  784. [source,kotlin,role="secondary"]
  785. ----
  786. import org.springframework.security.config.annotation.web.invoke
  787. @Configuration
  788. @EnableWebSecurity
  789. class SecurityConfig {
  790. @Bean
  791. fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  792. http {
  793. // ...
  794. oauth2Login { }
  795. oauth2Client { }
  796. }
  797. return http.build()
  798. }
  799. }
  800. ----
  801. =====
  802. In addition to the above configuration, the application requires at least one `ClientRegistration` to be configured through the use of a `ClientRegistrationRepository` bean.
  803. The following example configures an `InMemoryClientRegistrationRepository` bean using Spring Boot configuration properties:
  804. [source,yaml]
  805. ----
  806. spring:
  807. security:
  808. oauth2:
  809. client:
  810. registration:
  811. my-combined-client:
  812. provider: my-auth-server
  813. client-id: my-client-id
  814. client-secret: my-client-secret
  815. authorization-grant-type: authorization_code
  816. scope: openid,profile,message.read,message.write
  817. provider:
  818. my-auth-server:
  819. issuer-uri: https://my-auth-server.com
  820. ----
  821. [NOTE]
  822. ====
  823. The main difference between the previous examples (<<oauth2-client-log-users-in>>, <<oauth2-client-access-protected-resources>>) and this one is what is configured via the `scope` property, which combines the standard scopes `openid` and `profile` with the custom scopes `message.read` and `message.write`.
  824. ====
  825. In addition to configuring Spring Security to support OAuth2 Client features, you will also need to decide how you will be accessing protected resources and configure your application accordingly.
  826. Spring Security provides implementations of `OAuth2AuthorizedClientManager` for obtaining access tokens that can be used to access protected resources.
  827. [TIP]
  828. ====
  829. Spring Security registers a default `OAuth2AuthorizedClientManager` bean for you when one does not exist.
  830. ====
  831. The easiest way to use an `OAuth2AuthorizedClientManager` is via a `ClientHttpRequestInterceptor` that intercepts requests through a `RestClient`, which is already available when `spring-web` is on the classpath.
  832. The following example uses the default `OAuth2AuthorizedClientManager` to configure a `RestClient` capable of accessing protected resources by placing `Bearer` tokens in the `Authorization` header of each request:
  833. .Configure `RestClient` with `ClientHttpRequestInterceptor`
  834. [tabs]
  835. =====
  836. Java::
  837. +
  838. [source,java,role="primary"]
  839. ----
  840. @Configuration
  841. public class RestClientConfig {
  842. @Bean
  843. public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  844. OAuth2ClientHttpRequestInterceptor requestInterceptor =
  845. new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
  846. requestInterceptor.setClientRegistrationIdResolver(clientRegistrationIdResolver());
  847. return RestClient.builder()
  848. .requestInterceptor(requestInterceptor)
  849. .build();
  850. }
  851. private static ClientRegistrationIdResolver clientRegistrationIdResolver() {
  852. return (request) -> {
  853. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  854. return (authentication instanceof OAuth2AuthenticationToken principal)
  855. ? principal.getAuthorizedClientRegistrationId()
  856. : null;
  857. };
  858. }
  859. }
  860. ----
  861. Kotlin::
  862. +
  863. [source,kotlin,role="secondary"]
  864. ----
  865. @Configuration
  866. class RestClientConfig {
  867. @Bean
  868. fun restClient(authorizedClientManager: OAuth2AuthorizedClientManager): RestClient {
  869. val requestInterceptor = OAuth2ClientHttpRequestInterceptor(authorizedClientManager)
  870. requestInterceptor.setClientRegistrationIdResolver(clientRegistrationIdResolver())
  871. return RestClient.builder()
  872. .requestInterceptor(requestInterceptor)
  873. .build()
  874. }
  875. private fun clientRegistrationIdResolver(): OAuth2ClientHttpRequestInterceptor.ClientRegistrationIdResolver {
  876. return OAuth2ClientHttpRequestInterceptor.ClientRegistrationIdResolver { request ->
  877. val authentication = SecurityContextHolder.getContext().authentication
  878. if (authentication is OAuth2AuthenticationToken) {
  879. authentication.authorizedClientRegistrationId
  880. } else {
  881. null
  882. }
  883. }
  884. }
  885. }
  886. ----
  887. =====
  888. This configured `RestClient` can be used as in the following example:
  889. [[oauth2-client-accessing-protected-resources-current-user-example]]
  890. .Use `RestClient` to Access Protected Resources (Current User)
  891. [tabs]
  892. =====
  893. Java::
  894. +
  895. [source,java,role="primary"]
  896. ----
  897. @RestController
  898. public class MessagesController {
  899. private final RestClient restClient;
  900. public MessagesController(RestClient restClient) {
  901. this.restClient = restClient;
  902. }
  903. @GetMapping("/messages")
  904. public ResponseEntity<List<Message>> messages() {
  905. Message[] messages = this.restClient.get()
  906. .uri("http://localhost:8090/messages")
  907. .retrieve()
  908. .body(Message[].class);
  909. return ResponseEntity.ok(Arrays.asList(messages));
  910. }
  911. public record Message(String message) {
  912. }
  913. }
  914. ----
  915. Kotlin::
  916. +
  917. [source,kotlin,role="secondary"]
  918. ----
  919. import org.springframework.web.client.body
  920. @RestController
  921. class MessagesController(private val restClient: RestClient) {
  922. @GetMapping("/messages")
  923. fun messages(): ResponseEntity<List<Message>> {
  924. val messages = restClient.get()
  925. .uri("http://localhost:8090/messages")
  926. .retrieve()
  927. .body<Array<Message>>()!!
  928. .toList()
  929. return ResponseEntity.ok(messages)
  930. }
  931. data class Message(val message: String)
  932. }
  933. ----
  934. =====
  935. [NOTE]
  936. ====
  937. Unlike the <<oauth2-client-accessing-protected-resources-example,previous example>>, notice that we do not need to tell Spring Security about the `clientRegistrationId` we'd like to use.
  938. This is because it can be derived from the currently logged in user.
  939. ====
  940. [[oauth2-client-client-credentials]]
  941. === Use the Client Credentials Grant
  942. [NOTE]
  943. ====
  944. This section focuses on additional considerations for the client credentials grant type.
  945. See <<oauth2-client-access-protected-resources>> for general setup and usage with all grant types.
  946. ====
  947. The https://tools.ietf.org/html/rfc6749#section-1.3.4[client credentials grant] allows a client to obtain an `access_token` on behalf of itself.
  948. The client credentials grant is a simple flow that does not involve a resource owner (i.e. a user).
  949. [WARNING]
  950. ====
  951. It is important to note that typical use of the client credentials grant implies that any request (or user) can potentially obtain an access token and make protected resources requests to a resource server.
  952. Exercise caution when designing applications to ensure that users cannot make unauthorized requests since every request will be able to obtain an access token.
  953. ====
  954. When obtaining access tokens within a web application where users can log in, the default behavior of Spring Security is to obtain an access token per user.
  955. [NOTE]
  956. ====
  957. By default, access tokens are scoped to the principal name of the current user which means every user will receive a unique access token.
  958. ====
  959. Clients using the client credentials grant typically require access tokens to be scoped to the application instead of to individual users so there is only one access token per application.
  960. In order to scope access tokens to the application, you will need to set a strategy for resolving a custom principal name.
  961. The following example does this by configuring a `RestClient` with the `RequestAttributePrincipalResolver`:
  962. .Configure `RestClient` for `client_credentials`
  963. [tabs]
  964. =====
  965. Java::
  966. +
  967. [source,java,role="primary"]
  968. ----
  969. @Configuration
  970. public class RestClientConfig {
  971. @Bean
  972. public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager) {
  973. OAuth2ClientHttpRequestInterceptor requestInterceptor =
  974. new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
  975. requestInterceptor.setPrincipalResolver(new RequestAttributePrincipalResolver());
  976. return RestClient.builder()
  977. .requestInterceptor(requestInterceptor)
  978. .build();
  979. }
  980. }
  981. ----
  982. Kotlin::
  983. +
  984. [source,kotlin,role="secondary"]
  985. ----
  986. @Configuration
  987. class RestClientConfig {
  988. @Bean
  989. fun restClient(authorizedClientManager: OAuth2AuthorizedClientManager): RestClient {
  990. val requestInterceptor = OAuth2ClientHttpRequestInterceptor(authorizedClientManager)
  991. requestInterceptor.setPrincipalResolver(RequestAttributePrincipalResolver())
  992. return RestClient.builder()
  993. .requestInterceptor(requestInterceptor)
  994. .build()
  995. }
  996. }
  997. ----
  998. =====
  999. With the above configuration in place, a principal name can be specified for each request.
  1000. The following example demonstrates how to scope access tokens to the application by specifying a principal name:
  1001. .Scope Access Tokens to the Application
  1002. [tabs]
  1003. =====
  1004. Java::
  1005. +
  1006. [source,java,role="primary"]
  1007. ----
  1008. import static org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver.clientRegistrationId;
  1009. import static org.springframework.security.oauth2.client.web.client.RequestAttributePrincipalResolver.principal;
  1010. @RestController
  1011. public class MessagesController {
  1012. private final RestClient restClient;
  1013. public MessagesController(RestClient restClient) {
  1014. this.restClient = restClient;
  1015. }
  1016. @GetMapping("/messages")
  1017. public ResponseEntity<List<Message>> messages() {
  1018. Message[] messages = this.restClient.get()
  1019. .uri("http://localhost:8090/messages")
  1020. .attributes(clientRegistrationId("my-oauth2-client"))
  1021. .attributes(principal("my-application"))
  1022. .retrieve()
  1023. .body(Message[].class);
  1024. return ResponseEntity.ok(Arrays.asList(messages));
  1025. }
  1026. public record Message(String message) {
  1027. }
  1028. }
  1029. ----
  1030. Kotlin::
  1031. +
  1032. [source,kotlin,role="secondary"]
  1033. ----
  1034. import org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver.clientRegistrationId
  1035. import org.springframework.security.oauth2.client.web.client.RequestAttributePrincipalResolver.principal
  1036. import org.springframework.web.client.body
  1037. @RestController
  1038. class MessagesController(private val restClient: RestClient) {
  1039. @GetMapping("/messages")
  1040. fun messages(): ResponseEntity<List<Message>> {
  1041. val messages = restClient.get()
  1042. .uri("http://localhost:8090/messages")
  1043. .attributes(clientRegistrationId("my-oauth2-client"))
  1044. .attributes(principal("my-application"))
  1045. .retrieve()
  1046. .body<Array<Message>>()!!
  1047. .toList()
  1048. return ResponseEntity.ok(messages)
  1049. }
  1050. data class Message(val message: String)
  1051. }
  1052. ----
  1053. =====
  1054. [NOTE]
  1055. ====
  1056. When specifying a principal name via attributes as in the above example, there will only be a single access token and it will be used for all requests.
  1057. ====
  1058. [[oauth2-client-enable-extension-grant-type]]
  1059. === Enable an Extension Grant Type
  1060. A common use case involves enabling and/or configuring an extension grant type.
  1061. For example, Spring Security provides support for the `jwt-bearer` and `token-exchange` grant types, but does not enable them by default because they are not part of the core OAuth 2.0 specification.
  1062. With Spring Security 6.2 and later, we can simply publish a bean for one or more `OAuth2AuthorizedClientProvider` and they will be picked up automatically.
  1063. The following example simply enables the `jwt-bearer` grant type:
  1064. .Enable `jwt-bearer` Grant Type
  1065. [tabs]
  1066. =====
  1067. Java::
  1068. +
  1069. [source,java,role="primary"]
  1070. ----
  1071. @Configuration
  1072. public class SecurityConfig {
  1073. @Bean
  1074. public OAuth2AuthorizedClientProvider jwtBearer() {
  1075. return new JwtBearerOAuth2AuthorizedClientProvider();
  1076. }
  1077. }
  1078. ----
  1079. Kotlin::
  1080. +
  1081. [source,kotlin,role="secondary"]
  1082. ----
  1083. @Configuration
  1084. class SecurityConfig {
  1085. @Bean
  1086. fun jwtBearer(): OAuth2AuthorizedClientProvider {
  1087. return JwtBearerOAuth2AuthorizedClientProvider()
  1088. }
  1089. }
  1090. ----
  1091. =====
  1092. A default `OAuth2AuthorizedClientManager` will be published automatically by Spring Security when one is not already provided.
  1093. [TIP]
  1094. ====
  1095. Any custom `OAuth2AuthorizedClientProvider` bean will also be picked up and applied to the provided `OAuth2AuthorizedClientManager` after the default grant types.
  1096. ====
  1097. In order to achieve the above configuration prior to Spring Security 6.2, we had to publish this bean ourselves and ensure we re-enabled default grant types as well.
  1098. To understand what is being configured behind the scenes, here's what the configuration might have looked like:
  1099. .Enable `jwt-bearer` Grant Type (prior to 6.2)
  1100. [tabs]
  1101. =====
  1102. Java::
  1103. +
  1104. [source,java,role="primary"]
  1105. ----
  1106. @Configuration
  1107. public class SecurityConfig {
  1108. @Bean
  1109. public OAuth2AuthorizedClientManager authorizedClientManager(
  1110. ClientRegistrationRepository clientRegistrationRepository,
  1111. OAuth2AuthorizedClientRepository authorizedClientRepository) {
  1112. OAuth2AuthorizedClientProvider authorizedClientProvider =
  1113. OAuth2AuthorizedClientProviderBuilder.builder()
  1114. .authorizationCode()
  1115. .refreshToken()
  1116. .clientCredentials()
  1117. .provider(new JwtBearerOAuth2AuthorizedClientProvider())
  1118. .build();
  1119. DefaultOAuth2AuthorizedClientManager authorizedClientManager =
  1120. new DefaultOAuth2AuthorizedClientManager(
  1121. clientRegistrationRepository, authorizedClientRepository);
  1122. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  1123. return authorizedClientManager;
  1124. }
  1125. }
  1126. ----
  1127. Kotlin::
  1128. +
  1129. [source,kotlin,role="secondary"]
  1130. ----
  1131. @Configuration
  1132. class SecurityConfig {
  1133. @Bean
  1134. fun authorizedClientManager(
  1135. clientRegistrationRepository: ClientRegistrationRepository,
  1136. authorizedClientRepository: OAuth2AuthorizedClientRepository
  1137. ): OAuth2AuthorizedClientManager {
  1138. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  1139. .authorizationCode()
  1140. .refreshToken()
  1141. .clientCredentials()
  1142. .provider(JwtBearerOAuth2AuthorizedClientProvider())
  1143. .build()
  1144. val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
  1145. clientRegistrationRepository, authorizedClientRepository
  1146. )
  1147. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  1148. return authorizedClientManager
  1149. }
  1150. }
  1151. ----
  1152. =====
  1153. [[oauth2-client-customize-existing-grant-type]]
  1154. === Customize an Existing Grant Type
  1155. The ability to <<oauth2-client-enable-extension-grant-type,enable extension grant types>> by publishing a bean also provides the opportunity for customizing an existing grant type without the need to re-define the defaults.
  1156. For example, if we want to customize the clock skew of the `OAuth2AuthorizedClientProvider` for the `client_credentials` grant, we can simply publish a bean like so:
  1157. .Customize Client Credentials Grant Type
  1158. [tabs]
  1159. =====
  1160. Java::
  1161. +
  1162. [source,java,role="primary"]
  1163. ----
  1164. @Configuration
  1165. public class SecurityConfig {
  1166. @Bean
  1167. public OAuth2AuthorizedClientProvider clientCredentials() {
  1168. ClientCredentialsOAuth2AuthorizedClientProvider authorizedClientProvider =
  1169. new ClientCredentialsOAuth2AuthorizedClientProvider();
  1170. authorizedClientProvider.setClockSkew(Duration.ofMinutes(5));
  1171. return authorizedClientProvider;
  1172. }
  1173. }
  1174. ----
  1175. Kotlin::
  1176. +
  1177. [source,kotlin,role="secondary"]
  1178. ----
  1179. @Configuration
  1180. class SecurityConfig {
  1181. @Bean
  1182. fun clientCredentials(): OAuth2AuthorizedClientProvider {
  1183. val authorizedClientProvider = ClientCredentialsOAuth2AuthorizedClientProvider()
  1184. authorizedClientProvider.setClockSkew(Duration.ofMinutes(5))
  1185. return authorizedClientProvider
  1186. }
  1187. }
  1188. ----
  1189. =====
  1190. [[oauth2-client-customize-request-parameters]]
  1191. === Customize Token Request Parameters
  1192. The need to customize request parameters when obtaining an access token is fairly common.
  1193. For example, let's say we want to add a custom `audience` parameter to the token request because the provider requires this parameter for the `authorization_code` grant.
  1194. With Spring Security 6.2 and later, we can simply publish a bean of type `OAuth2AccessTokenResponseClient` with the generic type `OAuth2AuthorizationCodeGrantRequest` and it will be used by Spring Security to configure OAuth2 Client components.
  1195. The following example customizes token request parameters for the `authorization_code` grant without the DSL:
  1196. .Customize Token Request Parameters for Authorization Code Grant
  1197. [tabs]
  1198. =====
  1199. Java::
  1200. +
  1201. [source,java,role="primary"]
  1202. ----
  1203. @Configuration
  1204. public class SecurityConfig {
  1205. @Bean
  1206. public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> authorizationCodeAccessTokenResponseClient() {
  1207. RestClientAuthorizationCodeTokenResponseClient accessTokenResponseClient =
  1208. new RestClientAuthorizationCodeTokenResponseClient();
  1209. accessTokenResponseClient.addParametersConverter(parametersConverter());
  1210. return accessTokenResponseClient;
  1211. }
  1212. private static Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter() {
  1213. return (grantRequest) -> {
  1214. MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
  1215. parameters.set("audience", "xyz_value");
  1216. return parameters;
  1217. };
  1218. }
  1219. }
  1220. ----
  1221. Kotlin::
  1222. +
  1223. [source,kotlin,role="secondary"]
  1224. ----
  1225. @Configuration
  1226. class SecurityConfig {
  1227. @Bean
  1228. fun authorizationCodeAccessTokenResponseClient(): OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> {
  1229. val accessTokenResponseClient = RestClientAuthorizationCodeTokenResponseClient()
  1230. accessTokenResponseClient.addParametersConverter(parametersConverter())
  1231. return accessTokenResponseClient
  1232. }
  1233. private fun parametersConverter(): Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> {
  1234. return Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> { grantRequest ->
  1235. LinkedMultiValueMap<String, String>().also { parameters ->
  1236. parameters["audience"] = "xyz_value"
  1237. }
  1238. }
  1239. }
  1240. }
  1241. ----
  1242. =====
  1243. [TIP]
  1244. ====
  1245. Notice that we don't need to customize the `SecurityFilterChain` bean in this case, and can stick with the defaults.
  1246. If using Spring Boot with no additional customizations, we can actually omit the `SecurityFilterChain` bean entirely.
  1247. ====
  1248. Prior to Spring Security 6.2, we had to ensure that this customization was applied for both OAuth2 Login (if we are using this feature) and OAuth2 Client components using the Spring Security DSL.
  1249. To understand what is being configured behind the scenes, here's what the configuration might have looked like:
  1250. .Customize Token Request Parameters for Authorization Code Grant (prior to 6.2)
  1251. [tabs]
  1252. =====
  1253. Java::
  1254. +
  1255. [source,java,role="primary"]
  1256. ----
  1257. @Configuration
  1258. @EnableWebSecurity
  1259. public class SecurityConfig {
  1260. @Bean
  1261. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  1262. RestClientAuthorizationCodeTokenResponseClient accessTokenResponseClient =
  1263. new RestClientAuthorizationCodeTokenResponseClient();
  1264. accessTokenResponseClient.addParametersConverter(parametersConverter());
  1265. http
  1266. .authorizeHttpRequests((authorize) -> authorize
  1267. .anyRequest().authenticated()
  1268. )
  1269. .oauth2Login((oauth2Login) -> oauth2Login
  1270. .tokenEndpoint((tokenEndpoint) -> tokenEndpoint
  1271. .accessTokenResponseClient(accessTokenResponseClient)
  1272. )
  1273. )
  1274. .oauth2Client((oauth2Client) -> oauth2Client
  1275. .authorizationCodeGrant((authorizationCode) -> authorizationCode
  1276. .accessTokenResponseClient(accessTokenResponseClient)
  1277. )
  1278. );
  1279. return http.build();
  1280. }
  1281. private static Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter() {
  1282. // ...
  1283. }
  1284. }
  1285. ----
  1286. Kotlin::
  1287. +
  1288. [source,kotlin,role="secondary"]
  1289. ----
  1290. import org.springframework.security.config.annotation.web.invoke
  1291. @Configuration
  1292. @EnableWebSecurity
  1293. class SecurityConfig {
  1294. @Bean
  1295. fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  1296. val tokenResponseClient = RestClientAuthorizationCodeTokenResponseClient()
  1297. tokenResponseClient.addParametersConverter(parametersConverter())
  1298. http {
  1299. authorizeHttpRequests {
  1300. authorize(anyRequest, authenticated)
  1301. }
  1302. oauth2Login {
  1303. tokenEndpoint {
  1304. accessTokenResponseClient = tokenResponseClient
  1305. }
  1306. }
  1307. oauth2Client {
  1308. authorizationCodeGrant {
  1309. accessTokenResponseClient = tokenResponseClient
  1310. }
  1311. }
  1312. }
  1313. return http.build()
  1314. }
  1315. private fun parametersConverter(): Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> {
  1316. // ...
  1317. }
  1318. }
  1319. ----
  1320. =====
  1321. For other grant types we can publish additional `OAuth2AccessTokenResponseClient` beans to override the defaults.
  1322. For example, to customize token requests for the `client_credentials` grant we can publish the following bean:
  1323. .Customize Token Request Parameters for Client Credentials Grant
  1324. [tabs]
  1325. =====
  1326. Java::
  1327. +
  1328. [source,java,role="primary"]
  1329. ----
  1330. @Configuration
  1331. public class SecurityConfig {
  1332. @Bean
  1333. public OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsAccessTokenResponseClient() {
  1334. RestClientClientCredentialsTokenResponseClient accessTokenResponseClient =
  1335. new RestClientClientCredentialsTokenResponseClient();
  1336. accessTokenResponseClient.addParametersConverter(parametersConverter());
  1337. return accessTokenResponseClient;
  1338. }
  1339. private static Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter() {
  1340. // ...
  1341. }
  1342. }
  1343. ----
  1344. Kotlin::
  1345. +
  1346. [source,kotlin,role="secondary"]
  1347. ----
  1348. @Configuration
  1349. class SecurityConfig {
  1350. @Bean
  1351. fun clientCredentialsAccessTokenResponseClient(): OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> {
  1352. val accessTokenResponseClient = RestClientClientCredentialsTokenResponseClient()
  1353. accessTokenResponseClient.addParametersConverter(parametersConverter())
  1354. return accessTokenResponseClient
  1355. }
  1356. private fun parametersConverter(): Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> {
  1357. // ...
  1358. }
  1359. }
  1360. ----
  1361. =====
  1362. Spring Security automatically resolves the following generic types of `OAuth2AccessTokenResponseClient` beans:
  1363. * `OAuth2AuthorizationCodeGrantRequest` (see `RestClientAuthorizationCodeTokenResponseClient`)
  1364. * `OAuth2RefreshTokenGrantRequest` (see `RestClientRefreshTokenTokenResponseClient`)
  1365. * `OAuth2ClientCredentialsGrantRequest` (see `RestClientClientCredentialsTokenResponseClient`)
  1366. * `JwtBearerGrantRequest` (see `RestClientJwtBearerTokenResponseClient`)
  1367. * `TokenExchangeGrantRequest` (see `RestClientTokenExchangeTokenResponseClient`)
  1368. [TIP]
  1369. ====
  1370. Publishing a bean of type `OAuth2AccessTokenResponseClient<JwtBearerGrantRequest>` will automatically enable the `jwt-bearer` grant type without the need to <<oauth2-client-enable-extension-grant-type,configure it separately>>.
  1371. ====
  1372. [TIP]
  1373. ====
  1374. Publishing a bean of type `OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest>` will automatically enable the `token-exchange` grant type without the need to <<oauth2-client-enable-extension-grant-type,configure it separately>>.
  1375. ====
  1376. [[oauth2-client-customize-rest-client]]
  1377. === Customize the `RestClient` used by OAuth2 Client Components
  1378. Another common use case is the need to customize the `RestClient` used when obtaining an access token.
  1379. We might need to do this to customize processing of the response (via a custom `HttpMessageConverter`) or to apply proxy settings for a corporate network (via a customized `ClientHttpRequestFactory`).
  1380. With Spring Security 6.2 and later, we can simply publish beans of type `OAuth2AccessTokenResponseClient` and Spring Security will configure and publish an `OAuth2AuthorizedClientManager` bean for us.
  1381. The following example customizes the `RestClient` for all of the supported grant types:
  1382. .Customize `RestClient` for OAuth2 Client
  1383. [tabs]
  1384. =====
  1385. Java::
  1386. +
  1387. [source,java,role="primary"]
  1388. ----
  1389. @Configuration
  1390. public class SecurityConfig {
  1391. @Bean
  1392. public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> authorizationCodeAccessTokenResponseClient() {
  1393. RestClientAuthorizationCodeTokenResponseClient accessTokenResponseClient =
  1394. new RestClientAuthorizationCodeTokenResponseClient();
  1395. accessTokenResponseClient.setRestClient(restClient());
  1396. return accessTokenResponseClient;
  1397. }
  1398. @Bean
  1399. public OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenAccessTokenResponseClient() {
  1400. RestClientRefreshTokenTokenResponseClient accessTokenResponseClient =
  1401. new RestClientRefreshTokenTokenResponseClient();
  1402. accessTokenResponseClient.setRestClient(restClient());
  1403. return accessTokenResponseClient;
  1404. }
  1405. @Bean
  1406. public OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsAccessTokenResponseClient() {
  1407. RestClientClientCredentialsTokenResponseClient accessTokenResponseClient =
  1408. new RestClientClientCredentialsTokenResponseClient();
  1409. accessTokenResponseClient.setRestClient(restClient());
  1410. return accessTokenResponseClient;
  1411. }
  1412. @Bean
  1413. public OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerAccessTokenResponseClient() {
  1414. RestClientJwtBearerTokenResponseClient accessTokenResponseClient =
  1415. new RestClientJwtBearerTokenResponseClient();
  1416. accessTokenResponseClient.setRestClient(restClient());
  1417. return accessTokenResponseClient;
  1418. }
  1419. @Bean
  1420. public OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> tokenExchangeAccessTokenResponseClient() {
  1421. RestClientTokenExchangeTokenResponseClient accessTokenResponseClient =
  1422. new RestClientTokenExchangeTokenResponseClient();
  1423. accessTokenResponseClient.setRestClient(restClient());
  1424. return accessTokenResponseClient;
  1425. }
  1426. @Bean
  1427. public RestClient restClient() {
  1428. // ...
  1429. }
  1430. }
  1431. ----
  1432. Kotlin::
  1433. +
  1434. [source,kotlin,role="secondary"]
  1435. ----
  1436. @Configuration
  1437. class SecurityConfig {
  1438. @Bean
  1439. fun authorizationCodeAccessTokenResponseClient(): OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> {
  1440. val accessTokenResponseClient = RestClientAuthorizationCodeTokenResponseClient()
  1441. accessTokenResponseClient.setRestClient(restClient())
  1442. return accessTokenResponseClient
  1443. }
  1444. @Bean
  1445. fun refreshTokenAccessTokenResponseClient(): OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> {
  1446. val accessTokenResponseClient = RestClientRefreshTokenTokenResponseClient()
  1447. accessTokenResponseClient.setRestClient(restClient())
  1448. return accessTokenResponseClient
  1449. }
  1450. @Bean
  1451. fun clientCredentialsAccessTokenResponseClient(): OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> {
  1452. val accessTokenResponseClient = RestClientClientCredentialsTokenResponseClient()
  1453. accessTokenResponseClient.setRestClient(restClient())
  1454. return accessTokenResponseClient
  1455. }
  1456. @Bean
  1457. fun jwtBearerAccessTokenResponseClient(): OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> {
  1458. val accessTokenResponseClient = RestClientJwtBearerTokenResponseClient()
  1459. accessTokenResponseClient.setRestClient(restClient())
  1460. return accessTokenResponseClient
  1461. }
  1462. @Bean
  1463. fun tokenExchangeAccessTokenResponseClient(): OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> {
  1464. val accessTokenResponseClient = RestClientTokenExchangeTokenResponseClient()
  1465. accessTokenResponseClient.setRestClient(restClient())
  1466. return accessTokenResponseClient
  1467. }
  1468. @Bean
  1469. fun restClient(): RestClient {
  1470. // ...
  1471. }
  1472. }
  1473. ----
  1474. =====
  1475. A default `OAuth2AuthorizedClientManager` will be published automatically by Spring Security when one is not already provided.
  1476. [TIP]
  1477. ====
  1478. Notice that we don't need to customize the `SecurityFilterChain` bean in this case, and can stick with the defaults.
  1479. If using Spring Boot with no additional customizations, we can actually omit the `SecurityFilterChain` bean entirely.
  1480. ====
  1481. Prior to Spring Security 6.2, we had to ensure this customization was applied to both OAuth2 Login (if we are using this feature) and OAuth2 Client components.
  1482. We had to use both the Spring Security DSL (for the `authorization_code` grant) and publish a bean of type `OAuth2AuthorizedClientManager` for other grant types.
  1483. To understand what is being configured behind the scenes, here's what the configuration might have looked like:
  1484. .Customize `RestClient` for OAuth2 Client (prior to 6.2)
  1485. [tabs]
  1486. =====
  1487. Java::
  1488. +
  1489. [source,java,role="primary"]
  1490. ----
  1491. @Configuration
  1492. @EnableWebSecurity
  1493. public class SecurityConfig {
  1494. @Bean
  1495. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  1496. RestClientAuthorizationCodeTokenResponseClient accessTokenResponseClient =
  1497. new RestClientAuthorizationCodeTokenResponseClient();
  1498. accessTokenResponseClient.setRestClient(restClient());
  1499. http
  1500. // ...
  1501. .oauth2Login((oauth2Login) -> oauth2Login
  1502. .tokenEndpoint((tokenEndpoint) -> tokenEndpoint
  1503. .accessTokenResponseClient(accessTokenResponseClient)
  1504. )
  1505. )
  1506. .oauth2Client((oauth2Client) -> oauth2Client
  1507. .authorizationCodeGrant((authorizationCode) -> authorizationCode
  1508. .accessTokenResponseClient(accessTokenResponseClient)
  1509. )
  1510. );
  1511. return http.build();
  1512. }
  1513. @Bean
  1514. public OAuth2AuthorizedClientManager authorizedClientManager(
  1515. ClientRegistrationRepository clientRegistrationRepository,
  1516. OAuth2AuthorizedClientRepository authorizedClientRepository) {
  1517. RestClientRefreshTokenTokenResponseClient refreshTokenAccessTokenResponseClient =
  1518. new RestClientRefreshTokenTokenResponseClient();
  1519. refreshTokenAccessTokenResponseClient.setRestClient(restClient());
  1520. RestClientClientCredentialsTokenResponseClient clientCredentialsAccessTokenResponseClient =
  1521. new RestClientClientCredentialsTokenResponseClient();
  1522. clientCredentialsAccessTokenResponseClient.setRestClient(restClient());
  1523. RestClientJwtBearerTokenResponseClient jwtBearerAccessTokenResponseClient =
  1524. new RestClientJwtBearerTokenResponseClient();
  1525. jwtBearerAccessTokenResponseClient.setRestClient(restClient());
  1526. JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider =
  1527. new JwtBearerOAuth2AuthorizedClientProvider();
  1528. jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerAccessTokenResponseClient);
  1529. RestClientTokenExchangeTokenResponseClient tokenExchangeAccessTokenResponseClient =
  1530. new RestClientTokenExchangeTokenResponseClient();
  1531. tokenExchangeAccessTokenResponseClient.setRestClient(restClient());
  1532. TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider =
  1533. new TokenExchangeOAuth2AuthorizedClientProvider();
  1534. tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeAccessTokenResponseClient);
  1535. OAuth2AuthorizedClientProvider authorizedClientProvider =
  1536. OAuth2AuthorizedClientProviderBuilder.builder()
  1537. .authorizationCode()
  1538. .refreshToken((refreshToken) -> refreshToken
  1539. .accessTokenResponseClient(refreshTokenAccessTokenResponseClient)
  1540. )
  1541. .clientCredentials((clientCredentials) -> clientCredentials
  1542. .accessTokenResponseClient(clientCredentialsAccessTokenResponseClient)
  1543. )
  1544. .provider(jwtBearerAuthorizedClientProvider)
  1545. .provider(tokenExchangeAuthorizedClientProvider)
  1546. .build();
  1547. DefaultOAuth2AuthorizedClientManager authorizedClientManager =
  1548. new DefaultOAuth2AuthorizedClientManager(
  1549. clientRegistrationRepository, authorizedClientRepository);
  1550. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
  1551. return authorizedClientManager;
  1552. }
  1553. @Bean
  1554. public RestClient restClient() {
  1555. // ...
  1556. }
  1557. }
  1558. ----
  1559. Kotlin::
  1560. +
  1561. [source,kotlin,role="secondary"]
  1562. ----
  1563. import org.springframework.security.config.annotation.web.invoke
  1564. @Configuration
  1565. @EnableWebSecurity
  1566. class SecurityConfig {
  1567. @Bean
  1568. fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  1569. val tokenResponseClient = RestClientAuthorizationCodeTokenResponseClient()
  1570. tokenResponseClient.setRestClient(restClient())
  1571. http {
  1572. // ...
  1573. oauth2Login {
  1574. tokenEndpoint {
  1575. accessTokenResponseClient = tokenResponseClient
  1576. }
  1577. }
  1578. oauth2Client {
  1579. authorizationCodeGrant {
  1580. accessTokenResponseClient = tokenResponseClient
  1581. }
  1582. }
  1583. }
  1584. return http.build()
  1585. }
  1586. @Bean
  1587. fun authorizedClientManager(
  1588. clientRegistrationRepository: ClientRegistrationRepository?,
  1589. authorizedClientRepository: OAuth2AuthorizedClientRepository?
  1590. ): OAuth2AuthorizedClientManager {
  1591. val refreshTokenAccessTokenResponseClient = RestClientRefreshTokenTokenResponseClient()
  1592. refreshTokenAccessTokenResponseClient.setRestClient(restClient())
  1593. val clientCredentialsAccessTokenResponseClient = RestClientClientCredentialsTokenResponseClient()
  1594. clientCredentialsAccessTokenResponseClient.setRestClient(restClient())
  1595. val jwtBearerAccessTokenResponseClient = RestClientJwtBearerTokenResponseClient()
  1596. jwtBearerAccessTokenResponseClient.setRestClient(restClient())
  1597. val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
  1598. jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerAccessTokenResponseClient)
  1599. val tokenExchangeAccessTokenResponseClient = RestClientTokenExchangeTokenResponseClient()
  1600. tokenExchangeAccessTokenResponseClient.setRestClient(restClient())
  1601. val tokenExchangeAuthorizedClientProvider = TokenExchangeOAuth2AuthorizedClientProvider()
  1602. tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeAccessTokenResponseClient)
  1603. val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  1604. .authorizationCode()
  1605. .refreshToken { refreshToken ->
  1606. refreshToken.accessTokenResponseClient(refreshTokenAccessTokenResponseClient)
  1607. }
  1608. .clientCredentials { clientCredentials ->
  1609. clientCredentials.accessTokenResponseClient(clientCredentialsAccessTokenResponseClient)
  1610. }
  1611. .provider(jwtBearerAuthorizedClientProvider)
  1612. .provider(tokenExchangeAuthorizedClientProvider)
  1613. .build()
  1614. val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
  1615. clientRegistrationRepository, authorizedClientRepository
  1616. )
  1617. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
  1618. return authorizedClientManager
  1619. }
  1620. @Bean
  1621. fun restClient(): RestClient {
  1622. // ...
  1623. }
  1624. }
  1625. ----
  1626. =====
  1627. [[further-reading]]
  1628. == Further Reading
  1629. The preceding sections introduced Spring Security's support for OAuth2 with examples for common scenarios.
  1630. You can read more about OAuth2 Client and Resource Server in the following sections of the reference documentation:
  1631. * xref:servlet/oauth2/login/index.adoc[]
  1632. * xref:servlet/oauth2/client/index.adoc[]
  1633. * xref:servlet/oauth2/resource-server/index.adoc[]