authorization-grants.adoc 52 KB

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