authorization-grants.adoc 51 KB

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