authorization-grants.adoc 51 KB

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