2
0

authorization-grants.adoc 51 KB

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