advanced.adoc 31 KB

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