authorization-grants.adoc 52 KB

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