authorization-grants.adoc 52 KB

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