advanced.adoc 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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()`) can be mapped to a new set of `GrantedAuthority` instances, which are supplied to `OAuth2AuthenticationToken` when completing the authentication.
  364. [TIP]
  365. `OAuth2AuthenticationToken.getAuthorities()` is used for authorizing requests, such as in `hasRole('USER')` or `hasRole('ADMIN')`.
  366. There are a couple of options to choose from when mapping user authorities:
  367. * <<oauth2login-advanced-map-authorities-grantedauthoritiesmapper>>
  368. * <<oauth2login-advanced-map-authorities-oauth2userservice>>
  369. [[oauth2login-advanced-map-authorities-grantedauthoritiesmapper]]
  370. ==== Using a GrantedAuthoritiesMapper
  371. Provide an implementation of `GrantedAuthoritiesMapper` and configure it, as follows:
  372. .Granted Authorities Mapper Configuration
  373. ====
  374. .Java
  375. [source,java,role="primary"]
  376. ----
  377. @Configuration
  378. @EnableWebSecurity
  379. public class OAuth2LoginSecurityConfig {
  380. @Bean
  381. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  382. http
  383. .oauth2Login(oauth2 -> oauth2
  384. .userInfoEndpoint(userInfo -> userInfo
  385. .userAuthoritiesMapper(this.userAuthoritiesMapper())
  386. ...
  387. )
  388. );
  389. return http.build();
  390. }
  391. private GrantedAuthoritiesMapper userAuthoritiesMapper() {
  392. return (authorities) -> {
  393. Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
  394. authorities.forEach(authority -> {
  395. if (OidcUserAuthority.class.isInstance(authority)) {
  396. OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority;
  397. OidcIdToken idToken = oidcUserAuthority.getIdToken();
  398. OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();
  399. // Map the claims found in idToken and/or userInfo
  400. // to one or more GrantedAuthority's and add it to mappedAuthorities
  401. } else if (OAuth2UserAuthority.class.isInstance(authority)) {
  402. OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority;
  403. Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();
  404. // Map the attributes found in userAttributes
  405. // to one or more GrantedAuthority's and add it to mappedAuthorities
  406. }
  407. });
  408. return mappedAuthorities;
  409. };
  410. }
  411. }
  412. ----
  413. .Kotlin
  414. [source,kotlin,role="secondary"]
  415. ----
  416. @Configuration
  417. @EnableWebSecurity
  418. class OAuth2LoginSecurityConfig {
  419. @Bean
  420. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  421. http {
  422. oauth2Login {
  423. userInfoEndpoint {
  424. userAuthoritiesMapper = userAuthoritiesMapper()
  425. }
  426. }
  427. }
  428. return http.build()
  429. }
  430. private fun userAuthoritiesMapper(): GrantedAuthoritiesMapper = GrantedAuthoritiesMapper { authorities: Collection<GrantedAuthority> ->
  431. val mappedAuthorities = emptySet<GrantedAuthority>()
  432. authorities.forEach { authority ->
  433. if (authority is OidcUserAuthority) {
  434. val idToken = authority.idToken
  435. val userInfo = authority.userInfo
  436. // Map the claims found in idToken and/or userInfo
  437. // to one or more GrantedAuthority's and add it to mappedAuthorities
  438. } else if (authority is OAuth2UserAuthority) {
  439. val userAttributes = authority.attributes
  440. // Map the attributes found in userAttributes
  441. // to one or more GrantedAuthority's and add it to mappedAuthorities
  442. }
  443. }
  444. mappedAuthorities
  445. }
  446. }
  447. ----
  448. .Xml
  449. [source,xml,role="secondary"]
  450. ----
  451. <http>
  452. <oauth2-login user-authorities-mapper-ref="userAuthoritiesMapper"
  453. ...
  454. />
  455. </http>
  456. ----
  457. ====
  458. Alternatively, you can register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the configuration, as follows:
  459. .Granted Authorities Mapper Bean Configuration
  460. ====
  461. .Java
  462. [source,java,role="primary"]
  463. ----
  464. @Configuration
  465. @EnableWebSecurity
  466. public class OAuth2LoginSecurityConfig {
  467. @Bean
  468. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  469. http
  470. .oauth2Login(withDefaults());
  471. return http.build();
  472. }
  473. @Bean
  474. public GrantedAuthoritiesMapper userAuthoritiesMapper() {
  475. ...
  476. }
  477. }
  478. ----
  479. .Kotlin
  480. [source,kotlin,role="secondary"]
  481. ----
  482. @Configuration
  483. @EnableWebSecurity
  484. class OAuth2LoginSecurityConfig {
  485. @Bean
  486. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  487. http {
  488. oauth2Login { }
  489. }
  490. return http.build()
  491. }
  492. @Bean
  493. fun userAuthoritiesMapper(): GrantedAuthoritiesMapper {
  494. ...
  495. }
  496. }
  497. ----
  498. ====
  499. [[oauth2login-advanced-map-authorities-oauth2userservice]]
  500. ==== Delegation-based Strategy with OAuth2UserService
  501. 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).
  502. 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.
  503. The following example shows how to implement and configure a delegation-based strategy using an OpenID Connect 1.0 UserService:
  504. .OAuth2UserService Configuration
  505. ====
  506. .Java
  507. [source,java,role="primary"]
  508. ----
  509. @Configuration
  510. @EnableWebSecurity
  511. public class OAuth2LoginSecurityConfig {
  512. @Bean
  513. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  514. http
  515. .oauth2Login(oauth2 -> oauth2
  516. .userInfoEndpoint(userInfo -> userInfo
  517. .oidcUserService(this.oidcUserService())
  518. ...
  519. )
  520. );
  521. return http.build();
  522. }
  523. private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
  524. final OidcUserService delegate = new OidcUserService();
  525. return (userRequest) -> {
  526. // Delegate to the default implementation for loading a user
  527. OidcUser oidcUser = delegate.loadUser(userRequest);
  528. OAuth2AccessToken accessToken = userRequest.getAccessToken();
  529. Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
  530. // TODO
  531. // 1) Fetch the authority information from the protected resource using accessToken
  532. // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities
  533. // 3) Create a copy of oidcUser but use the mappedAuthorities instead
  534. oidcUser = new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());
  535. return oidcUser;
  536. };
  537. }
  538. }
  539. ----
  540. .Kotlin
  541. [source,kotlin,role="secondary"]
  542. ----
  543. @Configuration
  544. @EnableWebSecurity
  545. class OAuth2LoginSecurityConfig {
  546. @Bean
  547. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  548. http {
  549. oauth2Login {
  550. userInfoEndpoint {
  551. oidcUserService = oidcUserService()
  552. }
  553. }
  554. }
  555. return http.build()
  556. }
  557. @Bean
  558. fun oidcUserService(): OAuth2UserService<OidcUserRequest, OidcUser> {
  559. val delegate = OidcUserService()
  560. return OAuth2UserService { userRequest ->
  561. // Delegate to the default implementation for loading a user
  562. var oidcUser = delegate.loadUser(userRequest)
  563. val accessToken = userRequest.accessToken
  564. val mappedAuthorities = HashSet<GrantedAuthority>()
  565. // TODO
  566. // 1) Fetch the authority information from the protected resource using accessToken
  567. // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities
  568. // 3) Create a copy of oidcUser but use the mappedAuthorities instead
  569. oidcUser = DefaultOidcUser(mappedAuthorities, oidcUser.idToken, oidcUser.userInfo)
  570. oidcUser
  571. }
  572. }
  573. }
  574. ----
  575. .Xml
  576. [source,xml,role="secondary"]
  577. ----
  578. <http>
  579. <oauth2-login oidc-user-service-ref="oidcUserService"
  580. ...
  581. />
  582. </http>
  583. ----
  584. ====
  585. [[oauth2login-advanced-oauth2-user-service]]
  586. === OAuth 2.0 UserService
  587. `DefaultOAuth2UserService` is an implementation of an `OAuth2UserService` that supports standard OAuth 2.0 Provider's.
  588. [NOTE]
  589. ====
  590. `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`.
  591. ====
  592. `DefaultOAuth2UserService` uses a `RestOperations` instance when requesting the user attributes at the UserInfo Endpoint.
  593. If you need to customize the pre-processing of the UserInfo Request, you can provide `DefaultOAuth2UserService.setRequestEntityConverter()` with a custom `Converter<OAuth2UserRequest, RequestEntity<?>>`.
  594. The default implementation `OAuth2UserRequestEntityConverter` builds a `RequestEntity` representation of a UserInfo Request that sets the `OAuth2AccessToken` in the `Authorization` header by default.
  595. 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`.
  596. The default `RestOperations` is configured as follows:
  597. ====
  598. [source,java]
  599. ----
  600. RestTemplate restTemplate = new RestTemplate();
  601. restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
  602. ----
  603. ====
  604. `OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error (400 Bad Request).
  605. It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`.
  606. Whether you customize `DefaultOAuth2UserService` or provide your own implementation of `OAuth2UserService`, you need to configure it as follows:
  607. ====
  608. .Java
  609. [source,java,role="primary"]
  610. ----
  611. @Configuration
  612. @EnableWebSecurity
  613. public class OAuth2LoginSecurityConfig {
  614. @Bean
  615. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  616. http
  617. .oauth2Login(oauth2 -> oauth2
  618. .userInfoEndpoint(userInfo -> userInfo
  619. .userService(this.oauth2UserService())
  620. ...
  621. )
  622. );
  623. return http.build();
  624. }
  625. private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
  626. ...
  627. }
  628. }
  629. ----
  630. .Kotlin
  631. [source,kotlin,role="secondary"]
  632. ----
  633. @Configuration
  634. @EnableWebSecurity
  635. class OAuth2LoginSecurityConfig {
  636. @Bean
  637. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  638. http {
  639. oauth2Login {
  640. userInfoEndpoint {
  641. userService = oauth2UserService()
  642. // ...
  643. }
  644. }
  645. }
  646. return http.build()
  647. }
  648. private fun oauth2UserService(): OAuth2UserService<OAuth2UserRequest, OAuth2User> {
  649. // ...
  650. }
  651. }
  652. ----
  653. ====
  654. [[oauth2login-advanced-oidc-user-service]]
  655. === OpenID Connect 1.0 UserService
  656. `OidcUserService` is an implementation of an `OAuth2UserService` that supports OpenID Connect 1.0 Provider's.
  657. The `OidcUserService` leverages the `DefaultOAuth2UserService` when requesting the user attributes at the UserInfo Endpoint.
  658. 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`.
  659. 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:
  660. ====
  661. .Java
  662. [source,java,role="primary"]
  663. ----
  664. @Configuration
  665. @EnableWebSecurity
  666. public class OAuth2LoginSecurityConfig {
  667. @Bean
  668. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  669. http
  670. .oauth2Login(oauth2 -> oauth2
  671. .userInfoEndpoint(userInfo -> userInfo
  672. .oidcUserService(this.oidcUserService())
  673. ...
  674. )
  675. );
  676. return http.build();
  677. }
  678. private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
  679. ...
  680. }
  681. }
  682. ----
  683. .Kotlin
  684. [source,kotlin,role="secondary"]
  685. ----
  686. @Configuration
  687. @EnableWebSecurity
  688. class OAuth2LoginSecurityConfig {
  689. @Bean
  690. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  691. http {
  692. oauth2Login {
  693. userInfoEndpoint {
  694. oidcUserService = oidcUserService()
  695. // ...
  696. }
  697. }
  698. }
  699. return http.build()
  700. }
  701. private fun oidcUserService(): OAuth2UserService<OidcUserRequest, OidcUser> {
  702. // ...
  703. }
  704. }
  705. ----
  706. ====
  707. [[oauth2login-advanced-idtoken-verify]]
  708. == ID Token Signature Verification
  709. 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.
  710. 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).
  711. The `OidcIdTokenDecoderFactory` provides a `JwtDecoder` used for `OidcIdToken` signature verification. The default algorithm is `RS256` but may be different when assigned during client registration.
  712. For these cases, you can configure a resolver to return the expected JWS algorithm assigned for a specific client.
  713. 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`
  714. The following code shows how to configure the `OidcIdTokenDecoderFactory` `@Bean` to default to `MacAlgorithm.HS256` for all `ClientRegistration` instances:
  715. ====
  716. .Java
  717. [source,java,role="primary"]
  718. ----
  719. @Bean
  720. public JwtDecoderFactory<ClientRegistration> idTokenDecoderFactory() {
  721. OidcIdTokenDecoderFactory idTokenDecoderFactory = new OidcIdTokenDecoderFactory();
  722. idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> MacAlgorithm.HS256);
  723. return idTokenDecoderFactory;
  724. }
  725. ----
  726. .Kotlin
  727. [source,kotlin,role="secondary"]
  728. ----
  729. @Bean
  730. fun idTokenDecoderFactory(): JwtDecoderFactory<ClientRegistration?> {
  731. val idTokenDecoderFactory = OidcIdTokenDecoderFactory()
  732. idTokenDecoderFactory.setJwsAlgorithmResolver { MacAlgorithm.HS256 }
  733. return idTokenDecoderFactory
  734. }
  735. ----
  736. ====
  737. [NOTE]
  738. ====
  739. 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.
  740. ====
  741. [TIP]
  742. ====
  743. 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.
  744. ====
  745. [[oauth2login-advanced-oidc-logout]]
  746. == OpenID Connect 1.0 Logout
  747. OpenID Connect Session Management 1.0 allows the ability to log out the end user at the Provider by using the Client.
  748. One of the strategies available is https://openid.net/specs/openid-connect-session-1_0.html#RPLogout[RP-Initiated Logout].
  749. 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].
  750. You can do so by configuring the `ClientRegistration` with the `issuer-uri`, as follows:
  751. ====
  752. [source,yaml]
  753. ----
  754. spring:
  755. security:
  756. oauth2:
  757. client:
  758. registration:
  759. okta:
  760. client-id: okta-client-id
  761. client-secret: okta-client-secret
  762. ...
  763. provider:
  764. okta:
  765. issuer-uri: https://dev-1234.oktapreview.com
  766. ----
  767. ====
  768. Also, you can configure `OidcClientInitiatedLogoutSuccessHandler`, which implements RP-Initiated Logout, as follows:
  769. ====
  770. .Java
  771. [source,java,role="primary"]
  772. ----
  773. @Configuration
  774. @EnableWebSecurity
  775. public class OAuth2LoginSecurityConfig {
  776. @Autowired
  777. private ClientRegistrationRepository clientRegistrationRepository;
  778. @Bean
  779. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  780. http
  781. .authorizeHttpRequests(authorize -> authorize
  782. .anyRequest().authenticated()
  783. )
  784. .oauth2Login(withDefaults())
  785. .logout(logout -> logout
  786. .logoutSuccessHandler(oidcLogoutSuccessHandler())
  787. );
  788. return http.build();
  789. }
  790. private LogoutSuccessHandler oidcLogoutSuccessHandler() {
  791. OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler =
  792. new OidcClientInitiatedLogoutSuccessHandler(this.clientRegistrationRepository);
  793. // Sets the location that the End-User's User Agent will be redirected to
  794. // after the logout has been performed at the Provider
  795. oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");
  796. return oidcLogoutSuccessHandler;
  797. }
  798. }
  799. ----
  800. .Kotlin
  801. [source,kotlin,role="secondary"]
  802. ----
  803. @Configuration
  804. @EnableWebSecurity
  805. class OAuth2LoginSecurityConfig {
  806. @Autowired
  807. private lateinit var clientRegistrationRepository: ClientRegistrationRepository
  808. @Bean
  809. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  810. http {
  811. authorizeRequests {
  812. authorize(anyRequest, authenticated)
  813. }
  814. oauth2Login { }
  815. logout {
  816. logoutSuccessHandler = oidcLogoutSuccessHandler()
  817. }
  818. }
  819. return http.build()
  820. }
  821. private fun oidcLogoutSuccessHandler(): LogoutSuccessHandler {
  822. val oidcLogoutSuccessHandler = OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository)
  823. // Sets the location that the End-User's User Agent will be redirected to
  824. // after the logout has been performed at the Provider
  825. oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}")
  826. return oidcLogoutSuccessHandler
  827. }
  828. }
  829. ----
  830. ====
  831. [NOTE]
  832. ====
  833. `OidcClientInitiatedLogoutSuccessHandler` supports the `+{baseUrl}+` placeholder.
  834. If used, the application's base URL, such as `https://app.example.org`, replaces it at request time.
  835. ====