2
0

authorization-grants.adoc 51 KB

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