advanced.adoc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. [[oauth2login-advanced]]
  2. = Advanced Configuration
  3. `HttpSecurity.oauth2Login()` provides a number of configuration options for customizing OAuth 2.0 Login.
  4. The main configuration options are grouped into their protocol endpoint counterparts.
  5. For example, `oauth2Login().authorizationEndpoint()` allows configuring the _Authorization Endpoint_, whereas `oauth2Login().tokenEndpoint()` allows configuring the _Token Endpoint_.
  6. The following code shows an example:
  7. .Advanced OAuth2 Login Configuration
  8. ====
  9. .Java
  10. [source,java,role="primary"]
  11. ----
  12. @EnableWebSecurity
  13. public class OAuth2LoginSecurityConfig {
  14. @Bean
  15. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  16. http
  17. .oauth2Login(oauth2 -> oauth2
  18. .authorizationEndpoint(authorization -> authorization
  19. ...
  20. )
  21. .redirectionEndpoint(redirection -> redirection
  22. ...
  23. )
  24. .tokenEndpoint(token -> token
  25. ...
  26. )
  27. .userInfoEndpoint(userInfo -> userInfo
  28. ...
  29. )
  30. );
  31. return http.build();
  32. }
  33. }
  34. ----
  35. .Kotlin
  36. [source,kotlin,role="secondary"]
  37. ----
  38. @EnableWebSecurity
  39. class OAuth2LoginSecurityConfig {
  40. @Bean
  41. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  42. http {
  43. oauth2Login {
  44. authorizationEndpoint {
  45. ...
  46. }
  47. redirectionEndpoint {
  48. ...
  49. }
  50. tokenEndpoint {
  51. ...
  52. }
  53. userInfoEndpoint {
  54. ...
  55. }
  56. }
  57. }
  58. return http.build()
  59. }
  60. }
  61. ----
  62. ====
  63. The main goal of the `oauth2Login()` DSL was to closely align with the naming, as defined in the specifications.
  64. The OAuth 2.0 Authorization Framework defines the https://tools.ietf.org/html/rfc6749#section-3[Protocol Endpoints] as follows:
  65. The authorization process uses two authorization server endpoints (HTTP resources):
  66. * Authorization Endpoint: Used by the client to obtain authorization from the resource owner through user-agent redirection.
  67. * Token Endpoint: Used by the client to exchange an authorization grant for an access token, typically with client authentication.
  68. The authorization process also uses one client endpoint:
  69. * Redirection Endpoint: Used by the authorization server to return responses that contain authorization credentials to the client through the resource owner user-agent.
  70. The OpenID Connect Core 1.0 specification defines the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] as follows:
  71. The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns claims about the authenticated end-user.
  72. To obtain the requested claims about the end-user, the client makes a request to the UserInfo Endpoint by using an access token obtained through OpenID Connect Authentication.
  73. These claims are normally represented by a JSON object that contains a collection of name-value pairs for the claims.
  74. The following code shows the complete configuration options available for the `oauth2Login()` DSL:
  75. .OAuth2 Login Configuration Options
  76. ====
  77. .Java
  78. [source,java,role="primary"]
  79. ----
  80. @EnableWebSecurity
  81. public class OAuth2LoginSecurityConfig {
  82. @Bean
  83. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  84. http
  85. .oauth2Login(oauth2 -> oauth2
  86. .clientRegistrationRepository(this.clientRegistrationRepository())
  87. .authorizedClientRepository(this.authorizedClientRepository())
  88. .authorizedClientService(this.authorizedClientService())
  89. .loginPage("/login")
  90. .authorizationEndpoint(authorization -> authorization
  91. .baseUri(this.authorizationRequestBaseUri())
  92. .authorizationRequestRepository(this.authorizationRequestRepository())
  93. .authorizationRequestResolver(this.authorizationRequestResolver())
  94. )
  95. .redirectionEndpoint(redirection -> redirection
  96. .baseUri(this.authorizationResponseBaseUri())
  97. )
  98. .tokenEndpoint(token -> token
  99. .accessTokenResponseClient(this.accessTokenResponseClient())
  100. )
  101. .userInfoEndpoint(userInfo -> userInfo
  102. .userAuthoritiesMapper(this.userAuthoritiesMapper())
  103. .userService(this.oauth2UserService())
  104. .oidcUserService(this.oidcUserService())
  105. )
  106. );
  107. return http.build();
  108. }
  109. }
  110. ----
  111. .Kotlin
  112. [source,kotlin,role="secondary"]
  113. ----
  114. @EnableWebSecurity
  115. class OAuth2LoginSecurityConfig {
  116. @Bean
  117. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  118. http {
  119. oauth2Login {
  120. clientRegistrationRepository = clientRegistrationRepository()
  121. authorizedClientRepository = authorizedClientRepository()
  122. authorizedClientService = authorizedClientService()
  123. loginPage = "/login"
  124. authorizationEndpoint {
  125. baseUri = authorizationRequestBaseUri()
  126. authorizationRequestRepository = authorizationRequestRepository()
  127. authorizationRequestResolver = authorizationRequestResolver()
  128. }
  129. redirectionEndpoint {
  130. baseUri = authorizationResponseBaseUri()
  131. }
  132. tokenEndpoint {
  133. accessTokenResponseClient = accessTokenResponseClient()
  134. }
  135. userInfoEndpoint {
  136. userAuthoritiesMapper = userAuthoritiesMapper()
  137. userService = oauth2UserService()
  138. oidcUserService = oidcUserService()
  139. }
  140. }
  141. }
  142. return http.build()
  143. }
  144. }
  145. ----
  146. ====
  147. In addition to the `oauth2Login()` DSL, XML configuration is also supported.
  148. The following code shows the complete configuration options available in the xref:servlet/appendix/namespace/http.adoc#nsa-oauth2-login[ security namespace]:
  149. .OAuth2 Login XML Configuration Options
  150. ====
  151. [source,xml]
  152. ----
  153. <http>
  154. <oauth2-login client-registration-repository-ref="clientRegistrationRepository"
  155. authorized-client-repository-ref="authorizedClientRepository"
  156. authorized-client-service-ref="authorizedClientService"
  157. authorization-request-repository-ref="authorizationRequestRepository"
  158. authorization-request-resolver-ref="authorizationRequestResolver"
  159. access-token-response-client-ref="accessTokenResponseClient"
  160. user-authorities-mapper-ref="userAuthoritiesMapper"
  161. user-service-ref="oauth2UserService"
  162. oidc-user-service-ref="oidcUserService"
  163. login-processing-url="/login/oauth2/code/*"
  164. login-page="/login"
  165. authentication-success-handler-ref="authenticationSuccessHandler"
  166. authentication-failure-handler-ref="authenticationFailureHandler"
  167. jwt-decoder-factory-ref="jwtDecoderFactory"/>
  168. </http>
  169. ----
  170. ====
  171. The following sections go into more detail on each of the configuration options available:
  172. * <<oauth2login-advanced-login-page>>
  173. * <<oauth2login-advanced-redirection-endpoint>>
  174. * <<oauth2login-advanced-userinfo-endpoint>>
  175. * <<oauth2login-advanced-idtoken-verify>>
  176. * <<oauth2login-advanced-oidc-logout>>
  177. [[oauth2login-advanced-login-page]]
  178. == OAuth 2.0 Login Page
  179. By default, the OAuth 2.0 Login Page is auto-generated by the `DefaultLoginPageGeneratingFilter`.
  180. The default login page shows each configured OAuth Client with its `ClientRegistration.clientName` as a link, which is capable of initiating the Authorization Request (or OAuth 2.0 Login).
  181. [NOTE]
  182. ====
  183. For `DefaultLoginPageGeneratingFilter` to show links for configured OAuth Clients, the registered `ClientRegistrationRepository` needs to also implement `Iterable<ClientRegistration>`.
  184. See `InMemoryClientRegistrationRepository` for reference.
  185. ====
  186. The link's destination for each OAuth Client defaults to the following:
  187. `+OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/{registrationId}"+`
  188. The following line shows an example:
  189. ====
  190. [source,html]
  191. ----
  192. <a href="/oauth2/authorization/google">Google</a>
  193. ----
  194. ====
  195. To override the default login page, configure `oauth2Login().loginPage()` and (optionally) `oauth2Login().authorizationEndpoint().baseUri()`.
  196. The following listing shows an example:
  197. .OAuth2 Login Page Configuration
  198. ====
  199. .Java
  200. [source,java,role="primary"]
  201. ----
  202. @EnableWebSecurity
  203. public class OAuth2LoginSecurityConfig {
  204. @Bean
  205. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  206. http
  207. .oauth2Login(oauth2 -> oauth2
  208. .loginPage("/login/oauth2")
  209. ...
  210. .authorizationEndpoint(authorization -> authorization
  211. .baseUri("/login/oauth2/authorization")
  212. ...
  213. )
  214. );
  215. return http.build();
  216. }
  217. }
  218. ----
  219. .Kotlin
  220. [source,kotlin,role="secondary"]
  221. ----
  222. @EnableWebSecurity
  223. class OAuth2LoginSecurityConfig {
  224. @Bean
  225. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  226. http {
  227. oauth2Login {
  228. loginPage = "/login/oauth2"
  229. authorizationEndpoint {
  230. baseUri = "/login/oauth2/authorization"
  231. }
  232. }
  233. }
  234. return http.build()
  235. }
  236. }
  237. ----
  238. .Xml
  239. [source,xml,role="secondary"]
  240. ----
  241. <http>
  242. <oauth2-login login-page="/login/oauth2"
  243. ...
  244. />
  245. </http>
  246. ----
  247. ====
  248. [IMPORTANT]
  249. ====
  250. You need to provide a `@Controller` with a `@RequestMapping("/login/oauth2")` that is capable of rendering the custom login page.
  251. ====
  252. [TIP]
  253. =====
  254. As noted earlier, configuring `oauth2Login().authorizationEndpoint().baseUri()` is optional.
  255. However, if you choose to customize it, ensure the link to each OAuth Client matches the `authorizationEndpoint().baseUri()`.
  256. The following line shows an example:
  257. ====
  258. [source,html]
  259. ----
  260. <a href="/login/oauth2/authorization/google">Google</a>
  261. ----
  262. ====
  263. =====
  264. [[oauth2login-advanced-redirection-endpoint]]
  265. == Redirection Endpoint
  266. The Redirection Endpoint is used by the Authorization Server for returning the Authorization Response (which contains the authorization credentials) to the client through the Resource Owner user-agent.
  267. [TIP]
  268. ====
  269. OAuth 2.0 Login leverages the Authorization Code Grant.
  270. Therefore, the authorization credential is the authorization code.
  271. ====
  272. The default Authorization Response `baseUri` (redirection endpoint) is `*/login/oauth2/code/**`, which is defined in `OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI`.
  273. If you would like to customize the Authorization Response `baseUri`, configure it as follows:
  274. .Redirection Endpoint Configuration
  275. ====
  276. .Java
  277. [source,java,role="primary"]
  278. ----
  279. @EnableWebSecurity
  280. public class OAuth2LoginSecurityConfig {
  281. @Bean
  282. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  283. http
  284. .oauth2Login(oauth2 -> oauth2
  285. .redirectionEndpoint(redirection -> redirection
  286. .baseUri("/login/oauth2/callback/*")
  287. ...
  288. )
  289. );
  290. return http.build();
  291. }
  292. }
  293. ----
  294. .Kotlin
  295. [source,kotlin,role="secondary"]
  296. ----
  297. @EnableWebSecurity
  298. class OAuth2LoginSecurityConfig {
  299. @Bean
  300. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  301. http {
  302. oauth2Login {
  303. redirectionEndpoint {
  304. baseUri = "/login/oauth2/callback/*"
  305. }
  306. }
  307. }
  308. return http.build()
  309. }
  310. }
  311. ----
  312. .Xml
  313. [source,xml,role="secondary"]
  314. ----
  315. <http>
  316. <oauth2-login login-processing-url="/login/oauth2/callback/*"
  317. ...
  318. />
  319. </http>
  320. ----
  321. ====
  322. [IMPORTANT]
  323. =====
  324. You also need to ensure the `ClientRegistration.redirectUri` matches the custom Authorization Response `baseUri`.
  325. The following listing shows an example:
  326. ====
  327. .Java
  328. [source,java,role="primary",subs="-attributes"]
  329. ----
  330. return CommonOAuth2Provider.GOOGLE.getBuilder("google")
  331. .clientId("google-client-id")
  332. .clientSecret("google-client-secret")
  333. .redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}")
  334. .build();
  335. ----
  336. .Kotlin
  337. [source,kotlin,role="secondary",subs="-attributes"]
  338. ----
  339. return CommonOAuth2Provider.GOOGLE.getBuilder("google")
  340. .clientId("google-client-id")
  341. .clientSecret("google-client-secret")
  342. .redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}")
  343. .build()
  344. ----
  345. ====
  346. =====
  347. [[oauth2login-advanced-userinfo-endpoint]]
  348. == UserInfo Endpoint
  349. The UserInfo Endpoint includes a number of configuration options, as described in the following sub-sections:
  350. * <<oauth2login-advanced-map-authorities>>
  351. * <<oauth2login-advanced-oauth2-user-service>>
  352. * <<oauth2login-advanced-oidc-user-service>>
  353. [[oauth2login-advanced-map-authorities]]
  354. === Mapping User Authorities
  355. After the user successfully authenticates with the OAuth 2.0 Provider, the `OAuth2User.getAuthorities()` (or `OidcUser.getAuthorities()`) can be mapped to a new set of `GrantedAuthority` instances, which are supplied to `OAuth2AuthenticationToken` when completing the authentication.
  356. [TIP]
  357. `OAuth2AuthenticationToken.getAuthorities()` is used for authorizing requests, such as in `hasRole('USER')` or `hasRole('ADMIN')`.
  358. There are a couple of options to choose from when mapping user authorities:
  359. * <<oauth2login-advanced-map-authorities-grantedauthoritiesmapper>>
  360. * <<oauth2login-advanced-map-authorities-oauth2userservice>>
  361. [[oauth2login-advanced-map-authorities-grantedauthoritiesmapper]]
  362. ==== Using a GrantedAuthoritiesMapper
  363. Provide an implementation of `GrantedAuthoritiesMapper` and configure it, as follows:
  364. .Granted Authorities Mapper Configuration
  365. ====
  366. .Java
  367. [source,java,role="primary"]
  368. ----
  369. @EnableWebSecurity
  370. public class OAuth2LoginSecurityConfig {
  371. @Bean
  372. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  373. http
  374. .oauth2Login(oauth2 -> oauth2
  375. .userInfoEndpoint(userInfo -> userInfo
  376. .userAuthoritiesMapper(this.userAuthoritiesMapper())
  377. ...
  378. )
  379. );
  380. return http.build();
  381. }
  382. private GrantedAuthoritiesMapper userAuthoritiesMapper() {
  383. return (authorities) -> {
  384. Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
  385. authorities.forEach(authority -> {
  386. if (OidcUserAuthority.class.isInstance(authority)) {
  387. OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority;
  388. OidcIdToken idToken = oidcUserAuthority.getIdToken();
  389. OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();
  390. // Map the claims found in idToken and/or userInfo
  391. // to one or more GrantedAuthority's and add it to mappedAuthorities
  392. } else if (OAuth2UserAuthority.class.isInstance(authority)) {
  393. OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority;
  394. Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();
  395. // Map the attributes found in userAttributes
  396. // to one or more GrantedAuthority's and add it to mappedAuthorities
  397. }
  398. });
  399. return mappedAuthorities;
  400. };
  401. }
  402. }
  403. ----
  404. .Kotlin
  405. [source,kotlin,role="secondary"]
  406. ----
  407. @EnableWebSecurity
  408. class OAuth2LoginSecurityConfig {
  409. @Bean
  410. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  411. http {
  412. oauth2Login {
  413. userInfoEndpoint {
  414. userAuthoritiesMapper = userAuthoritiesMapper()
  415. }
  416. }
  417. }
  418. return http.build()
  419. }
  420. private fun userAuthoritiesMapper(): GrantedAuthoritiesMapper = GrantedAuthoritiesMapper { authorities: Collection<GrantedAuthority> ->
  421. val mappedAuthorities = emptySet<GrantedAuthority>()
  422. authorities.forEach { authority ->
  423. if (authority is OidcUserAuthority) {
  424. val idToken = authority.idToken
  425. val userInfo = authority.userInfo
  426. // Map the claims found in idToken and/or userInfo
  427. // to one or more GrantedAuthority's and add it to mappedAuthorities
  428. } else if (authority is OAuth2UserAuthority) {
  429. val userAttributes = authority.attributes
  430. // Map the attributes found in userAttributes
  431. // to one or more GrantedAuthority's and add it to mappedAuthorities
  432. }
  433. }
  434. mappedAuthorities
  435. }
  436. }
  437. ----
  438. .Xml
  439. [source,xml,role="secondary"]
  440. ----
  441. <http>
  442. <oauth2-login user-authorities-mapper-ref="userAuthoritiesMapper"
  443. ...
  444. />
  445. </http>
  446. ----
  447. ====
  448. Alternatively, you can register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the configuration, as follows:
  449. .Granted Authorities Mapper Bean Configuration
  450. ====
  451. .Java
  452. [source,java,role="primary"]
  453. ----
  454. @EnableWebSecurity
  455. public class OAuth2LoginSecurityConfig {
  456. @Bean
  457. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  458. http
  459. .oauth2Login(withDefaults());
  460. return http.build();
  461. }
  462. @Bean
  463. public GrantedAuthoritiesMapper userAuthoritiesMapper() {
  464. ...
  465. }
  466. }
  467. ----
  468. .Kotlin
  469. [source,kotlin,role="secondary"]
  470. ----
  471. @EnableWebSecurity
  472. class OAuth2LoginSecurityConfig {
  473. @Bean
  474. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  475. http {
  476. oauth2Login { }
  477. }
  478. return http.build()
  479. }
  480. @Bean
  481. fun userAuthoritiesMapper(): GrantedAuthoritiesMapper {
  482. ...
  483. }
  484. }
  485. ----
  486. ====
  487. [[oauth2login-advanced-map-authorities-oauth2userservice]]
  488. ==== Delegation-based Strategy with OAuth2UserService
  489. This strategy is advanced compared to using a `GrantedAuthoritiesMapper`. However, it is also more flexible, as it gives you access to the `OAuth2UserRequest` and `OAuth2User` (when using an OAuth 2.0 UserService) or `OidcUserRequest` and `OidcUser` (when using an OpenID Connect 1.0 UserService).
  490. The `OAuth2UserRequest` (and `OidcUserRequest`) provides you access to the associated `OAuth2AccessToken`, which is very useful in cases where the _delegator_ needs to fetch authority information from a protected resource before it can map the custom authorities for the user.
  491. The following example shows how to implement and configure a delegation-based strategy using an OpenID Connect 1.0 UserService:
  492. .OAuth2UserService Configuration
  493. ====
  494. .Java
  495. [source,java,role="primary"]
  496. ----
  497. @EnableWebSecurity
  498. public class OAuth2LoginSecurityConfig {
  499. @Bean
  500. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  501. http
  502. .oauth2Login(oauth2 -> oauth2
  503. .userInfoEndpoint(userInfo -> userInfo
  504. .oidcUserService(this.oidcUserService())
  505. ...
  506. )
  507. );
  508. return http.build();
  509. }
  510. private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
  511. final OidcUserService delegate = new OidcUserService();
  512. return (userRequest) -> {
  513. // Delegate to the default implementation for loading a user
  514. OidcUser oidcUser = delegate.loadUser(userRequest);
  515. OAuth2AccessToken accessToken = userRequest.getAccessToken();
  516. Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
  517. // TODO
  518. // 1) Fetch the authority information from the protected resource using accessToken
  519. // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities
  520. // 3) Create a copy of oidcUser but use the mappedAuthorities instead
  521. oidcUser = new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());
  522. return oidcUser;
  523. };
  524. }
  525. }
  526. ----
  527. .Kotlin
  528. [source,kotlin,role="secondary"]
  529. ----
  530. @EnableWebSecurity
  531. class OAuth2LoginSecurityConfig {
  532. @Bean
  533. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  534. http {
  535. oauth2Login {
  536. userInfoEndpoint {
  537. oidcUserService = oidcUserService()
  538. }
  539. }
  540. }
  541. return http.build()
  542. }
  543. @Bean
  544. fun oidcUserService(): OAuth2UserService<OidcUserRequest, OidcUser> {
  545. val delegate = OidcUserService()
  546. return OAuth2UserService { userRequest ->
  547. // Delegate to the default implementation for loading a user
  548. var oidcUser = delegate.loadUser(userRequest)
  549. val accessToken = userRequest.accessToken
  550. val mappedAuthorities = HashSet<GrantedAuthority>()
  551. // TODO
  552. // 1) Fetch the authority information from the protected resource using accessToken
  553. // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities
  554. // 3) Create a copy of oidcUser but use the mappedAuthorities instead
  555. oidcUser = DefaultOidcUser(mappedAuthorities, oidcUser.idToken, oidcUser.userInfo)
  556. oidcUser
  557. }
  558. }
  559. }
  560. ----
  561. .Xml
  562. [source,xml,role="secondary"]
  563. ----
  564. <http>
  565. <oauth2-login oidc-user-service-ref="oidcUserService"
  566. ...
  567. />
  568. </http>
  569. ----
  570. ====
  571. [[oauth2login-advanced-oauth2-user-service]]
  572. === OAuth 2.0 UserService
  573. `DefaultOAuth2UserService` is an implementation of an `OAuth2UserService` that supports standard OAuth 2.0 Provider's.
  574. [NOTE]
  575. ====
  576. `OAuth2UserService` obtains the user attributes of the end-user (the resource owner) from the UserInfo Endpoint (by using the access token granted to the client during the authorization flow) and returns an `AuthenticatedPrincipal` in the form of an `OAuth2User`.
  577. ====
  578. `DefaultOAuth2UserService` uses a `RestOperations` instance when requesting the user attributes at the UserInfo Endpoint.
  579. If you need to customize the pre-processing of the UserInfo Request, you can provide `DefaultOAuth2UserService.setRequestEntityConverter()` with a custom `Converter<OAuth2UserRequest, RequestEntity<?>>`.
  580. The default implementation `OAuth2UserRequestEntityConverter` builds a `RequestEntity` representation of a UserInfo Request that sets the `OAuth2AccessToken` in the `Authorization` header by default.
  581. On the other end, if you need to customize the post-handling of the UserInfo Response, you need to provide `DefaultOAuth2UserService.setRestOperations()` with a custom configured `RestOperations`.
  582. The default `RestOperations` is configured as follows:
  583. ====
  584. [source,java]
  585. ----
  586. RestTemplate restTemplate = new RestTemplate();
  587. restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
  588. ----
  589. ====
  590. `OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error (400 Bad Request).
  591. It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`.
  592. Whether you customize `DefaultOAuth2UserService` or provide your own implementation of `OAuth2UserService`, you need to configure it as follows:
  593. ====
  594. .Java
  595. [source,java,role="primary"]
  596. ----
  597. @EnableWebSecurity
  598. public class OAuth2LoginSecurityConfig {
  599. @Bean
  600. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  601. http
  602. .oauth2Login(oauth2 -> oauth2
  603. .userInfoEndpoint(userInfo -> userInfo
  604. .userService(this.oauth2UserService())
  605. ...
  606. )
  607. );
  608. return http.build();
  609. }
  610. private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
  611. ...
  612. }
  613. }
  614. ----
  615. .Kotlin
  616. [source,kotlin,role="secondary"]
  617. ----
  618. @EnableWebSecurity
  619. class OAuth2LoginSecurityConfig {
  620. @Bean
  621. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  622. http {
  623. oauth2Login {
  624. userInfoEndpoint {
  625. userService = oauth2UserService()
  626. // ...
  627. }
  628. }
  629. }
  630. return http.build()
  631. }
  632. private fun oauth2UserService(): OAuth2UserService<OAuth2UserRequest, OAuth2User> {
  633. // ...
  634. }
  635. }
  636. ----
  637. ====
  638. [[oauth2login-advanced-oidc-user-service]]
  639. === OpenID Connect 1.0 UserService
  640. `OidcUserService` is an implementation of an `OAuth2UserService` that supports OpenID Connect 1.0 Provider's.
  641. The `OidcUserService` leverages the `DefaultOAuth2UserService` when requesting the user attributes at the UserInfo Endpoint.
  642. If you need to customize the pre-processing of the UserInfo Request or the post-handling of the UserInfo Response, you need to provide `OidcUserService.setOauth2UserService()` with a custom configured `DefaultOAuth2UserService`.
  643. Whether you customize `OidcUserService` or provide your own implementation of `OAuth2UserService` for OpenID Connect 1.0 Provider's, you need to configure it as follows:
  644. ====
  645. .Java
  646. [source,java,role="primary"]
  647. ----
  648. @EnableWebSecurity
  649. public class OAuth2LoginSecurityConfig {
  650. @Bean
  651. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  652. http
  653. .oauth2Login(oauth2 -> oauth2
  654. .userInfoEndpoint(userInfo -> userInfo
  655. .oidcUserService(this.oidcUserService())
  656. ...
  657. )
  658. );
  659. return http.build();
  660. }
  661. private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
  662. ...
  663. }
  664. }
  665. ----
  666. .Kotlin
  667. [source,kotlin,role="secondary"]
  668. ----
  669. @EnableWebSecurity
  670. class OAuth2LoginSecurityConfig {
  671. @Bean
  672. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  673. http {
  674. oauth2Login {
  675. userInfoEndpoint {
  676. oidcUserService = oidcUserService()
  677. // ...
  678. }
  679. }
  680. }
  681. return http.build()
  682. }
  683. private fun oidcUserService(): OAuth2UserService<OidcUserRequest, OidcUser> {
  684. // ...
  685. }
  686. }
  687. ----
  688. ====
  689. [[oauth2login-advanced-idtoken-verify]]
  690. == ID Token Signature Verification
  691. OpenID Connect 1.0 Authentication introduces the https://openid.net/specs/openid-connect-core-1_0.html#IDToken[ID Token], which is a security token that contains Claims about the Authentication of an End-User by an Authorization Server when used by a Client.
  692. The ID Token is represented as a https://tools.ietf.org/html/rfc7519[JSON Web Token] (JWT) and MUST be signed by using https://tools.ietf.org/html/rfc7515[JSON Web Signature] (JWS).
  693. The `OidcIdTokenDecoderFactory` provides a `JwtDecoder` used for `OidcIdToken` signature verification. The default algorithm is `RS256` but may be different when assigned during client registration.
  694. For these cases, you can configure a resolver to return the expected JWS algorithm assigned for a specific client.
  695. The JWS algorithm resolver is a `Function` that accepts a `ClientRegistration` and returns the expected `JwsAlgorithm` for the client, such as `SignatureAlgorithm.RS256` or `MacAlgorithm.HS256`
  696. The following code shows how to configure the `OidcIdTokenDecoderFactory` `@Bean` to default to `MacAlgorithm.HS256` for all `ClientRegistration` instances:
  697. ====
  698. .Java
  699. [source,java,role="primary"]
  700. ----
  701. @Bean
  702. public JwtDecoderFactory<ClientRegistration> idTokenDecoderFactory() {
  703. OidcIdTokenDecoderFactory idTokenDecoderFactory = new OidcIdTokenDecoderFactory();
  704. idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> MacAlgorithm.HS256);
  705. return idTokenDecoderFactory;
  706. }
  707. ----
  708. .Kotlin
  709. [source,kotlin,role="secondary"]
  710. ----
  711. @Bean
  712. fun idTokenDecoderFactory(): JwtDecoderFactory<ClientRegistration?> {
  713. val idTokenDecoderFactory = OidcIdTokenDecoderFactory()
  714. idTokenDecoderFactory.setJwsAlgorithmResolver { MacAlgorithm.HS256 }
  715. return idTokenDecoderFactory
  716. }
  717. ----
  718. ====
  719. [NOTE]
  720. ====
  721. For MAC-based algorithms (such as `HS256`, `HS384`, or `HS512`), the `client-secret` that corresponds to the `client-id` is used as the symmetric key for signature verification.
  722. ====
  723. [TIP]
  724. ====
  725. If more than one `ClientRegistration` is configured for OpenID Connect 1.0 Authentication, the JWS algorithm resolver may evaluate the provided `ClientRegistration` to determine which algorithm to return.
  726. ====
  727. [[oauth2login-advanced-oidc-logout]]
  728. == OpenID Connect 1.0 Logout
  729. OpenID Connect Session Management 1.0 allows the ability to log out the end user at the Provider by using the Client.
  730. One of the strategies available is https://openid.net/specs/openid-connect-session-1_0.html#RPLogout[RP-Initiated Logout].
  731. If the OpenID Provider supports both Session Management and https://openid.net/specs/openid-connect-discovery-1_0.html[Discovery], the client can obtain the `end_session_endpoint` `URL` from the OpenID Provider's https://openid.net/specs/openid-connect-session-1_0.html#OPMetadata[Discovery Metadata].
  732. You can do so by configuring the `ClientRegistration` with the `issuer-uri`, as follows:
  733. ====
  734. [source,yaml]
  735. ----
  736. spring:
  737. security:
  738. oauth2:
  739. client:
  740. registration:
  741. okta:
  742. client-id: okta-client-id
  743. client-secret: okta-client-secret
  744. ...
  745. provider:
  746. okta:
  747. issuer-uri: https://dev-1234.oktapreview.com
  748. ----
  749. ====
  750. Also, you can configure `OidcClientInitiatedLogoutSuccessHandler`, which implements RP-Initiated Logout, as follows:
  751. ====
  752. .Java
  753. [source,java,role="primary"]
  754. ----
  755. @EnableWebSecurity
  756. public class OAuth2LoginSecurityConfig {
  757. @Autowired
  758. private ClientRegistrationRepository clientRegistrationRepository;
  759. @Bean
  760. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  761. http
  762. .authorizeHttpRequests(authorize -> authorize
  763. .anyRequest().authenticated()
  764. )
  765. .oauth2Login(withDefaults())
  766. .logout(logout -> logout
  767. .logoutSuccessHandler(oidcLogoutSuccessHandler())
  768. );
  769. return http.build();
  770. }
  771. private LogoutSuccessHandler oidcLogoutSuccessHandler() {
  772. OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler =
  773. new OidcClientInitiatedLogoutSuccessHandler(this.clientRegistrationRepository);
  774. // Sets the location that the End-User's User Agent will be redirected to
  775. // after the logout has been performed at the Provider
  776. oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");
  777. return oidcLogoutSuccessHandler;
  778. }
  779. }
  780. ----
  781. .Kotlin
  782. [source,kotlin,role="secondary"]
  783. ----
  784. @EnableWebSecurity
  785. class OAuth2LoginSecurityConfig {
  786. @Autowired
  787. private lateinit var clientRegistrationRepository: ClientRegistrationRepository
  788. @Bean
  789. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  790. http {
  791. authorizeRequests {
  792. authorize(anyRequest, authenticated)
  793. }
  794. oauth2Login { }
  795. logout {
  796. logoutSuccessHandler = oidcLogoutSuccessHandler()
  797. }
  798. }
  799. return http.build()
  800. }
  801. private fun oidcLogoutSuccessHandler(): LogoutSuccessHandler {
  802. val oidcLogoutSuccessHandler = OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository)
  803. // Sets the location that the End-User's User Agent will be redirected to
  804. // after the logout has been performed at the Provider
  805. oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}")
  806. return oidcLogoutSuccessHandler
  807. }
  808. }
  809. ----
  810. ====
  811. [NOTE]
  812. ====
  813. `OidcClientInitiatedLogoutSuccessHandler` supports the `+{baseUrl}+` placeholder.
  814. If used, the application's base URL, such as `https://app.example.org`, replaces it at request time.
  815. ====