advanced.adoc 30 KB

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