2
0

oauth2-login.adoc 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  1. [[oauth2login]]
  2. = OAuth 2.0 Login
  3. The OAuth 2.0 Login feature provides an application with the capability to have users log in to the application by using their existing account at an OAuth 2.0 Provider (e.g. GitHub) or OpenID Connect 1.0 Provider (such as Google).
  4. OAuth 2.0 Login implements the use cases: "Login with Google" or "Login with GitHub".
  5. NOTE: OAuth 2.0 Login is implemented by using the *Authorization Code Grant*, as specified in the https://tools.ietf.org/html/rfc6749#section-4.1[OAuth 2.0 Authorization Framework] and https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth[OpenID Connect Core 1.0].
  6. [[oauth2login-sample-boot]]
  7. == Spring Boot 2.x Sample
  8. Spring Boot 2.x brings full auto-configuration capabilities for OAuth 2.0 Login.
  9. This section shows how to configure the {gh-samples-url}/servlet/spring-boot/java/oauth2/login[*OAuth 2.0 Login sample*] using _Google_ as the _Authentication Provider_ and covers the following topics:
  10. * <<oauth2login-sample-initial-setup,Initial setup>>
  11. * <<oauth2login-sample-redirect-uri,Setting the redirect URI>>
  12. * <<oauth2login-sample-application-config,Configure application.yml>>
  13. * <<oauth2login-sample-boot-application,Boot up the application>>
  14. [[oauth2login-sample-initial-setup]]
  15. === Initial setup
  16. To use Google's OAuth 2.0 authentication system for login, you must set up a project in the Google API Console to obtain OAuth 2.0 credentials.
  17. NOTE: https://developers.google.com/identity/protocols/OpenIDConnect[Google's OAuth 2.0 implementation] for authentication conforms to the https://openid.net/connect/[OpenID Connect 1.0] specification and is https://openid.net/certification/[OpenID Certified].
  18. Follow the instructions on the https://developers.google.com/identity/protocols/OpenIDConnect[OpenID Connect] page, starting in the section, "Setting up OAuth 2.0".
  19. After completing the "Obtain OAuth 2.0 credentials" instructions, you should have a new OAuth Client with credentials consisting of a Client ID and a Client Secret.
  20. [[oauth2login-sample-redirect-uri]]
  21. === Setting the redirect URI
  22. The redirect URI is the path in the application that the end-user's user-agent is redirected back to after they have authenticated with Google and have granted access to the OAuth Client _(<<oauth2login-sample-initial-setup,created in the previous step>>)_ on the Consent page.
  23. In the "Set a redirect URI" sub-section, ensure that the *Authorized redirect URIs* field is set to `http://localhost:8080/login/oauth2/code/google`.
  24. TIP: The default redirect URI template is `+{baseUrl}/login/oauth2/code/{registrationId}+`.
  25. The *_registrationId_* is a unique identifier for the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration].
  26. IMPORTANT: If the OAuth Client is running behind a proxy server, it is recommended to check xref:features/exploits/http.adoc#http-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured.
  27. Also, see the supported xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`.
  28. [[oauth2login-sample-application-config]]
  29. === Configure application.yml
  30. Now that you have a new OAuth Client with Google, you need to configure the application to use the OAuth Client for the _authentication flow_.
  31. To do so:
  32. . Go to `application.yml` and set the following configuration:
  33. +
  34. [source,yaml]
  35. ----
  36. spring:
  37. security:
  38. oauth2:
  39. client:
  40. registration: <1>
  41. google: <2>
  42. client-id: google-client-id
  43. client-secret: google-client-secret
  44. ----
  45. +
  46. .OAuth Client properties
  47. ====
  48. <1> `spring.security.oauth2.client.registration` is the base property prefix for OAuth Client properties.
  49. <2> Following the base property prefix is the ID for the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration], such as google.
  50. ====
  51. . Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier.
  52. [[oauth2login-sample-boot-application]]
  53. === Boot up the application
  54. Launch the Spring Boot 2.x sample and go to `http://localhost:8080`.
  55. You are then redirected to the default _auto-generated_ login page, which displays a link for Google.
  56. Click on the Google link, and you are then redirected to Google for authentication.
  57. After authenticating with your Google account credentials, the next page presented to you is the Consent screen.
  58. The Consent screen asks you to either allow or deny access to the OAuth Client you created earlier.
  59. Click *Allow* to authorize the OAuth Client to access your email address and basic profile information.
  60. At this point, the OAuth Client retrieves your email address and basic profile information from the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session.
  61. [[oauth2login-boot-property-mappings]]
  62. == Spring Boot 2.x Property Mappings
  63. The following table outlines the mapping of the Spring Boot 2.x OAuth Client properties to the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration] properties.
  64. |===
  65. |Spring Boot 2.x |ClientRegistration
  66. |`spring.security.oauth2.client.registration._[registrationId]_`
  67. |`registrationId`
  68. |`spring.security.oauth2.client.registration._[registrationId]_.client-id`
  69. |`clientId`
  70. |`spring.security.oauth2.client.registration._[registrationId]_.client-secret`
  71. |`clientSecret`
  72. |`spring.security.oauth2.client.registration._[registrationId]_.client-authentication-method`
  73. |`clientAuthenticationMethod`
  74. |`spring.security.oauth2.client.registration._[registrationId]_.authorization-grant-type`
  75. |`authorizationGrantType`
  76. |`spring.security.oauth2.client.registration._[registrationId]_.redirect-uri`
  77. |`redirectUri`
  78. |`spring.security.oauth2.client.registration._[registrationId]_.scope`
  79. |`scopes`
  80. |`spring.security.oauth2.client.registration._[registrationId]_.client-name`
  81. |`clientName`
  82. |`spring.security.oauth2.client.provider._[providerId]_.authorization-uri`
  83. |`providerDetails.authorizationUri`
  84. |`spring.security.oauth2.client.provider._[providerId]_.token-uri`
  85. |`providerDetails.tokenUri`
  86. |`spring.security.oauth2.client.provider._[providerId]_.jwk-set-uri`
  87. |`providerDetails.jwkSetUri`
  88. |`spring.security.oauth2.client.provider._[providerId]_.issuer-uri`
  89. |`providerDetails.issuerUri`
  90. |`spring.security.oauth2.client.provider._[providerId]_.user-info-uri`
  91. |`providerDetails.userInfoEndpoint.uri`
  92. |`spring.security.oauth2.client.provider._[providerId]_.user-info-authentication-method`
  93. |`providerDetails.userInfoEndpoint.authenticationMethod`
  94. |`spring.security.oauth2.client.provider._[providerId]_.user-name-attribute`
  95. |`providerDetails.userInfoEndpoint.userNameAttributeName`
  96. |===
  97. [TIP]
  98. A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint], by specifying the `spring.security.oauth2.client.provider._[providerId]_.issuer-uri` property.
  99. [[oauth2login-common-oauth2-provider]]
  100. == CommonOAuth2Provider
  101. `CommonOAuth2Provider` pre-defines a set of default client properties for a number of well known providers: Google, GitHub, Facebook, and Okta.
  102. For example, the `authorization-uri`, `token-uri`, and `user-info-uri` do not change often for a Provider.
  103. Therefore, it makes sense to provide default values in order to reduce the required configuration.
  104. As demonstrated previously, when we <<oauth2login-sample-application-config,configured a Google client>>, only the `client-id` and `client-secret` properties are required.
  105. The following listing shows an example:
  106. [source,yaml]
  107. ----
  108. spring:
  109. security:
  110. oauth2:
  111. client:
  112. registration:
  113. google:
  114. client-id: google-client-id
  115. client-secret: google-client-secret
  116. ----
  117. [TIP]
  118. The auto-defaulting of client properties works seamlessly here because the `registrationId` (`google`) matches the `GOOGLE` `enum` (case-insensitive) in `CommonOAuth2Provider`.
  119. For cases where you may want to specify a different `registrationId`, such as `google-login`, you can still leverage auto-defaulting of client properties by configuring the `provider` property.
  120. The following listing shows an example:
  121. [source,yaml]
  122. ----
  123. spring:
  124. security:
  125. oauth2:
  126. client:
  127. registration:
  128. google-login: <1>
  129. provider: google <2>
  130. client-id: google-client-id
  131. client-secret: google-client-secret
  132. ----
  133. <1> The `registrationId` is set to `google-login`.
  134. <2> The `provider` property is set to `google`, which will leverage the auto-defaulting of client properties set in `CommonOAuth2Provider.GOOGLE.getBuilder()`.
  135. [[oauth2login-custom-provider-properties]]
  136. == Configuring Custom Provider Properties
  137. There are some OAuth 2.0 Providers that support multi-tenancy, which results in different protocol endpoints for each tenant (or sub-domain).
  138. For example, an OAuth Client registered with Okta is assigned to a specific sub-domain and have their own protocol endpoints.
  139. For these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: `spring.security.oauth2.client.provider._[providerId]_`.
  140. The following listing shows an example:
  141. [source,yaml]
  142. ----
  143. spring:
  144. security:
  145. oauth2:
  146. client:
  147. registration:
  148. okta:
  149. client-id: okta-client-id
  150. client-secret: okta-client-secret
  151. provider:
  152. okta: <1>
  153. authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize
  154. token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token
  155. user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo
  156. user-name-attribute: sub
  157. jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys
  158. ----
  159. <1> The base property (`spring.security.oauth2.client.provider.okta`) allows for custom configuration of protocol endpoint locations.
  160. [[oauth2login-override-boot-autoconfig]]
  161. == Overriding Spring Boot 2.x Auto-configuration
  162. The Spring Boot 2.x auto-configuration class for OAuth Client support is `OAuth2ClientAutoConfiguration`.
  163. It performs the following tasks:
  164. * Registers a `ClientRegistrationRepository` `@Bean` composed of `ClientRegistration`(s) from the configured OAuth Client properties.
  165. * Provides a `WebSecurityConfigurerAdapter` `@Configuration` and enables OAuth 2.0 Login through `httpSecurity.oauth2Login()`.
  166. If you need to override the auto-configuration based on your specific requirements, you may do so in the following ways:
  167. * <<oauth2login-register-clientregistrationrepository-bean,Register a ClientRegistrationRepository @Bean>>
  168. * <<oauth2login-provide-websecurityconfigureradapter,Provide a WebSecurityConfigurerAdapter>>
  169. * <<oauth2login-completely-override-autoconfiguration,Completely Override the Auto-configuration>>
  170. [[oauth2login-register-clientregistrationrepository-bean]]
  171. === Register a ClientRegistrationRepository @Bean
  172. The following example shows how to register a `ClientRegistrationRepository` `@Bean`:
  173. ====
  174. .Java
  175. [source,java,role="primary",attrs="-attributes"]
  176. ----
  177. @Configuration
  178. public class OAuth2LoginConfig {
  179. @Bean
  180. public ClientRegistrationRepository clientRegistrationRepository() {
  181. return new InMemoryClientRegistrationRepository(this.googleClientRegistration());
  182. }
  183. private ClientRegistration googleClientRegistration() {
  184. return ClientRegistration.withRegistrationId("google")
  185. .clientId("google-client-id")
  186. .clientSecret("google-client-secret")
  187. .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
  188. .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
  189. .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
  190. .scope("openid", "profile", "email", "address", "phone")
  191. .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
  192. .tokenUri("https://www.googleapis.com/oauth2/v4/token")
  193. .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
  194. .userNameAttributeName(IdTokenClaimNames.SUB)
  195. .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
  196. .clientName("Google")
  197. .build();
  198. }
  199. }
  200. ----
  201. .Kotlin
  202. [source,kotlin,role="secondary",attrs="-attributes"]
  203. ----
  204. @Configuration
  205. class OAuth2LoginConfig {
  206. @Bean
  207. fun clientRegistrationRepository(): ClientRegistrationRepository {
  208. return InMemoryClientRegistrationRepository(googleClientRegistration())
  209. }
  210. private fun googleClientRegistration(): ClientRegistration {
  211. return ClientRegistration.withRegistrationId("google")
  212. .clientId("google-client-id")
  213. .clientSecret("google-client-secret")
  214. .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
  215. .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
  216. .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
  217. .scope("openid", "profile", "email", "address", "phone")
  218. .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
  219. .tokenUri("https://www.googleapis.com/oauth2/v4/token")
  220. .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
  221. .userNameAttributeName(IdTokenClaimNames.SUB)
  222. .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
  223. .clientName("Google")
  224. .build()
  225. }
  226. }
  227. ----
  228. ====
  229. [[oauth2login-provide-websecurityconfigureradapter]]
  230. === Provide a WebSecurityConfigurerAdapter
  231. The following example shows how to provide a `WebSecurityConfigurerAdapter` with `@EnableWebSecurity` and enable OAuth 2.0 login through `httpSecurity.oauth2Login()`:
  232. .OAuth2 Login Configuration
  233. ====
  234. .Java
  235. [source,java,role="primary"]
  236. ----
  237. @EnableWebSecurity
  238. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  239. @Override
  240. protected void configure(HttpSecurity http) throws Exception {
  241. http
  242. .authorizeRequests(authorize -> authorize
  243. .anyRequest().authenticated()
  244. )
  245. .oauth2Login(withDefaults());
  246. }
  247. }
  248. ----
  249. .Kotlin
  250. [source,kotlin,role="secondary"]
  251. ----
  252. @EnableWebSecurity
  253. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  254. override fun configure(http: HttpSecurity) {
  255. http {
  256. authorizeRequests {
  257. authorize(anyRequest, authenticated)
  258. }
  259. oauth2Login { }
  260. }
  261. }
  262. }
  263. ----
  264. ====
  265. [[oauth2login-completely-override-autoconfiguration]]
  266. === Completely Override the Auto-configuration
  267. The following example shows how to completely override the auto-configuration by registering a `ClientRegistrationRepository` `@Bean` and providing a `WebSecurityConfigurerAdapter`.
  268. .Overriding the auto-configuration
  269. ====
  270. .Java
  271. [source,java,role="primary",attrs="-attributes"]
  272. ----
  273. @Configuration
  274. public class OAuth2LoginConfig {
  275. @EnableWebSecurity
  276. public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  277. @Override
  278. protected void configure(HttpSecurity http) throws Exception {
  279. http
  280. .authorizeRequests(authorize -> authorize
  281. .anyRequest().authenticated()
  282. )
  283. .oauth2Login(withDefaults());
  284. }
  285. }
  286. @Bean
  287. public ClientRegistrationRepository clientRegistrationRepository() {
  288. return new InMemoryClientRegistrationRepository(this.googleClientRegistration());
  289. }
  290. private ClientRegistration googleClientRegistration() {
  291. return ClientRegistration.withRegistrationId("google")
  292. .clientId("google-client-id")
  293. .clientSecret("google-client-secret")
  294. .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
  295. .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
  296. .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
  297. .scope("openid", "profile", "email", "address", "phone")
  298. .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
  299. .tokenUri("https://www.googleapis.com/oauth2/v4/token")
  300. .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
  301. .userNameAttributeName(IdTokenClaimNames.SUB)
  302. .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
  303. .clientName("Google")
  304. .build();
  305. }
  306. }
  307. ----
  308. .Kotlin
  309. [source,kotlin,role="secondary",attrs="-attributes"]
  310. ----
  311. @Configuration
  312. class OAuth2LoginConfig {
  313. @EnableWebSecurity
  314. class OAuth2LoginSecurityConfig: WebSecurityConfigurerAdapter() {
  315. override fun configure(http: HttpSecurity) {
  316. http {
  317. authorizeRequests {
  318. authorize(anyRequest, authenticated)
  319. }
  320. oauth2Login { }
  321. }
  322. }
  323. }
  324. @Bean
  325. fun clientRegistrationRepository(): ClientRegistrationRepository {
  326. return InMemoryClientRegistrationRepository(googleClientRegistration())
  327. }
  328. private fun googleClientRegistration(): ClientRegistration {
  329. return ClientRegistration.withRegistrationId("google")
  330. .clientId("google-client-id")
  331. .clientSecret("google-client-secret")
  332. .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
  333. .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
  334. .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
  335. .scope("openid", "profile", "email", "address", "phone")
  336. .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
  337. .tokenUri("https://www.googleapis.com/oauth2/v4/token")
  338. .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
  339. .userNameAttributeName(IdTokenClaimNames.SUB)
  340. .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
  341. .clientName("Google")
  342. .build()
  343. }
  344. }
  345. ----
  346. ====
  347. [[oauth2login-javaconfig-wo-boot]]
  348. == Java Configuration without Spring Boot 2.x
  349. If you are not able to use Spring Boot 2.x and would like to configure one of the pre-defined providers in `CommonOAuth2Provider` (for example, Google), apply the following configuration:
  350. .OAuth2 Login Configuration
  351. ====
  352. .Java
  353. [source,java,role="primary"]
  354. ----
  355. @Configuration
  356. public class OAuth2LoginConfig {
  357. @EnableWebSecurity
  358. public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  359. @Override
  360. protected void configure(HttpSecurity http) throws Exception {
  361. http
  362. .authorizeRequests(authorize -> authorize
  363. .anyRequest().authenticated()
  364. )
  365. .oauth2Login(withDefaults());
  366. }
  367. }
  368. @Bean
  369. public ClientRegistrationRepository clientRegistrationRepository() {
  370. return new InMemoryClientRegistrationRepository(this.googleClientRegistration());
  371. }
  372. @Bean
  373. public OAuth2AuthorizedClientService authorizedClientService(
  374. ClientRegistrationRepository clientRegistrationRepository) {
  375. return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
  376. }
  377. @Bean
  378. public OAuth2AuthorizedClientRepository authorizedClientRepository(
  379. OAuth2AuthorizedClientService authorizedClientService) {
  380. return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService);
  381. }
  382. private ClientRegistration googleClientRegistration() {
  383. return CommonOAuth2Provider.GOOGLE.getBuilder("google")
  384. .clientId("google-client-id")
  385. .clientSecret("google-client-secret")
  386. .build();
  387. }
  388. }
  389. ----
  390. .Kotlin
  391. [source,kotlin,role="secondary"]
  392. ----
  393. @Configuration
  394. open class OAuth2LoginConfig {
  395. @EnableWebSecurity
  396. open class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  397. override fun configure(http: HttpSecurity) {
  398. http {
  399. authorizeRequests {
  400. authorize(anyRequest, authenticated)
  401. }
  402. oauth2Login { }
  403. }
  404. }
  405. }
  406. @Bean
  407. open fun clientRegistrationRepository(): ClientRegistrationRepository {
  408. return InMemoryClientRegistrationRepository(googleClientRegistration())
  409. }
  410. @Bean
  411. open fun authorizedClientService(
  412. clientRegistrationRepository: ClientRegistrationRepository?
  413. ): OAuth2AuthorizedClientService {
  414. return InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository)
  415. }
  416. @Bean
  417. open fun authorizedClientRepository(
  418. authorizedClientService: OAuth2AuthorizedClientService?
  419. ): OAuth2AuthorizedClientRepository {
  420. return AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService)
  421. }
  422. private fun googleClientRegistration(): ClientRegistration {
  423. return CommonOAuth2Provider.GOOGLE.getBuilder("google")
  424. .clientId("google-client-id")
  425. .clientSecret("google-client-secret")
  426. .build()
  427. }
  428. }
  429. ----
  430. .Xml
  431. [source,xml,role="secondary"]
  432. ----
  433. <http auto-config="true">
  434. <intercept-url pattern="/**" access="authenticated"/>
  435. <oauth2-login authorized-client-repository-ref="authorizedClientRepository"/>
  436. </http>
  437. <client-registrations>
  438. <client-registration registration-id="google"
  439. client-id="google-client-id"
  440. client-secret="google-client-secret"
  441. provider-id="google"/>
  442. </client-registrations>
  443. <b:bean id="authorizedClientService"
  444. class="org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService"
  445. autowire="constructor"/>
  446. <b:bean id="authorizedClientRepository"
  447. class="org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository">
  448. <b:constructor-arg ref="authorizedClientService"/>
  449. </b:bean>
  450. ----
  451. ====
  452. [[oauth2login-advanced]]
  453. == Advanced Configuration
  454. `HttpSecurity.oauth2Login()` provides a number of configuration options for customizing OAuth 2.0 Login.
  455. The main configuration options are grouped into their protocol endpoint counterparts.
  456. For example, `oauth2Login().authorizationEndpoint()` allows configuring the _Authorization Endpoint_, whereas `oauth2Login().tokenEndpoint()` allows configuring the _Token Endpoint_.
  457. The following code shows an example:
  458. .Advanced OAuth2 Login Configuration
  459. ====
  460. .Java
  461. [source,java,role="primary"]
  462. ----
  463. @EnableWebSecurity
  464. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  465. @Override
  466. protected void configure(HttpSecurity http) throws Exception {
  467. http
  468. .oauth2Login(oauth2 -> oauth2
  469. .authorizationEndpoint(authorization -> authorization
  470. ...
  471. )
  472. .redirectionEndpoint(redirection -> redirection
  473. ...
  474. )
  475. .tokenEndpoint(token -> token
  476. ...
  477. )
  478. .userInfoEndpoint(userInfo -> userInfo
  479. ...
  480. )
  481. );
  482. }
  483. }
  484. ----
  485. .Kotlin
  486. [source,kotlin,role="secondary"]
  487. ----
  488. @EnableWebSecurity
  489. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  490. override fun configure(http: HttpSecurity) {
  491. http {
  492. oauth2Login {
  493. authorizationEndpoint {
  494. ...
  495. }
  496. redirectionEndpoint {
  497. ...
  498. }
  499. tokenEndpoint {
  500. ...
  501. }
  502. userInfoEndpoint {
  503. ...
  504. }
  505. }
  506. }
  507. }
  508. }
  509. ----
  510. ====
  511. The main goal of the `oauth2Login()` DSL was to closely align with the naming, as defined in the specifications.
  512. The OAuth 2.0 Authorization Framework defines the https://tools.ietf.org/html/rfc6749#section-3[Protocol Endpoints] as follows:
  513. The authorization process utilizes two authorization server endpoints (HTTP resources):
  514. * Authorization Endpoint: Used by the client to obtain authorization from the resource owner via user-agent redirection.
  515. * Token Endpoint: Used by the client to exchange an authorization grant for an access token, typically with client authentication.
  516. As well as one client endpoint:
  517. * Redirection Endpoint: Used by the authorization server to return responses containing authorization credentials to the client via the resource owner user-agent.
  518. The OpenID Connect Core 1.0 specification defines the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] as follows:
  519. The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns claims about the authenticated end-user.
  520. 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.
  521. These claims are normally represented by a JSON object that contains a collection of name-value pairs for the claims.
  522. The following code shows the complete configuration options available for the `oauth2Login()` DSL:
  523. .OAuth2 Login Configuration Options
  524. ====
  525. .Java
  526. [source,java,role="primary"]
  527. ----
  528. @EnableWebSecurity
  529. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  530. @Override
  531. protected void configure(HttpSecurity http) throws Exception {
  532. http
  533. .oauth2Login(oauth2 -> oauth2
  534. .clientRegistrationRepository(this.clientRegistrationRepository())
  535. .authorizedClientRepository(this.authorizedClientRepository())
  536. .authorizedClientService(this.authorizedClientService())
  537. .loginPage("/login")
  538. .authorizationEndpoint(authorization -> authorization
  539. .baseUri(this.authorizationRequestBaseUri())
  540. .authorizationRequestRepository(this.authorizationRequestRepository())
  541. .authorizationRequestResolver(this.authorizationRequestResolver())
  542. )
  543. .redirectionEndpoint(redirection -> redirection
  544. .baseUri(this.authorizationResponseBaseUri())
  545. )
  546. .tokenEndpoint(token -> token
  547. .accessTokenResponseClient(this.accessTokenResponseClient())
  548. )
  549. .userInfoEndpoint(userInfo -> userInfo
  550. .userAuthoritiesMapper(this.userAuthoritiesMapper())
  551. .userService(this.oauth2UserService())
  552. .oidcUserService(this.oidcUserService())
  553. )
  554. );
  555. }
  556. }
  557. ----
  558. .Kotlin
  559. [source,kotlin,role="secondary"]
  560. ----
  561. @EnableWebSecurity
  562. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  563. override fun configure(http: HttpSecurity) {
  564. http {
  565. oauth2Login {
  566. clientRegistrationRepository = clientRegistrationRepository()
  567. authorizedClientRepository = authorizedClientRepository()
  568. authorizedClientService = authorizedClientService()
  569. loginPage = "/login"
  570. authorizationEndpoint {
  571. baseUri = authorizationRequestBaseUri()
  572. authorizationRequestRepository = authorizationRequestRepository()
  573. authorizationRequestResolver = authorizationRequestResolver()
  574. }
  575. redirectionEndpoint {
  576. baseUri = authorizationResponseBaseUri()
  577. }
  578. tokenEndpoint {
  579. accessTokenResponseClient = accessTokenResponseClient()
  580. }
  581. userInfoEndpoint {
  582. userAuthoritiesMapper = userAuthoritiesMapper()
  583. userService = oauth2UserService()
  584. oidcUserService = oidcUserService()
  585. }
  586. }
  587. }
  588. }
  589. }
  590. ----
  591. ====
  592. In addition to the `oauth2Login()` DSL, XML configuration is also supported.
  593. The following code shows the complete configuration options available in the xref:servlet/appendix/namespace.adoc#nsa-oauth2-login[ security namespace]:
  594. .OAuth2 Login XML Configuration Options
  595. ====
  596. [source,xml]
  597. ----
  598. <http>
  599. <oauth2-login client-registration-repository-ref="clientRegistrationRepository"
  600. authorized-client-repository-ref="authorizedClientRepository"
  601. authorized-client-service-ref="authorizedClientService"
  602. authorization-request-repository-ref="authorizationRequestRepository"
  603. authorization-request-resolver-ref="authorizationRequestResolver"
  604. access-token-response-client-ref="accessTokenResponseClient"
  605. user-authorities-mapper-ref="userAuthoritiesMapper"
  606. user-service-ref="oauth2UserService"
  607. oidc-user-service-ref="oidcUserService"
  608. login-processing-url="/login/oauth2/code/*"
  609. login-page="/login"
  610. authentication-success-handler-ref="authenticationSuccessHandler"
  611. authentication-failure-handler-ref="authenticationFailureHandler"
  612. jwt-decoder-factory-ref="jwtDecoderFactory"/>
  613. </http>
  614. ----
  615. ====
  616. The following sections go into more detail on each of the configuration options available:
  617. * <<oauth2login-advanced-login-page, OAuth 2.0 Login Page>>
  618. * <<oauth2login-advanced-redirection-endpoint, Redirection Endpoint>>
  619. * <<oauth2login-advanced-userinfo-endpoint, UserInfo Endpoint>>
  620. [[oauth2login-advanced-login-page]]
  621. === OAuth 2.0 Login Page
  622. By default, the OAuth 2.0 Login Page is auto-generated by the `DefaultLoginPageGeneratingFilter`.
  623. 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).
  624. [NOTE]
  625. In order for `DefaultLoginPageGeneratingFilter` to show links for configured OAuth Clients, the registered `ClientRegistrationRepository` needs to also implement `Iterable<ClientRegistration>`.
  626. See `InMemoryClientRegistrationRepository` for reference.
  627. The link's destination for each OAuth Client defaults to the following:
  628. `+OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/{registrationId}"+`
  629. The following line shows an example:
  630. [source,html]
  631. ----
  632. <a href="/oauth2/authorization/google">Google</a>
  633. ----
  634. To override the default login page, configure `oauth2Login().loginPage()` and (optionally) `oauth2Login().authorizationEndpoint().baseUri()`.
  635. The following listing shows an example:
  636. .OAuth2 Login Page Configuration
  637. ====
  638. .Java
  639. [source,java,role="primary"]
  640. ----
  641. @EnableWebSecurity
  642. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  643. @Override
  644. protected void configure(HttpSecurity http) throws Exception {
  645. http
  646. .oauth2Login(oauth2 -> oauth2
  647. .loginPage("/login/oauth2")
  648. ...
  649. .authorizationEndpoint(authorization -> authorization
  650. .baseUri("/login/oauth2/authorization")
  651. ...
  652. )
  653. );
  654. }
  655. }
  656. ----
  657. .Kotlin
  658. [source,kotlin,role="secondary"]
  659. ----
  660. @EnableWebSecurity
  661. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  662. override fun configure(http: HttpSecurity) {
  663. http {
  664. oauth2Login {
  665. loginPage = "/login/oauth2"
  666. authorizationEndpoint {
  667. baseUri = "/login/oauth2/authorization"
  668. }
  669. }
  670. }
  671. }
  672. }
  673. ----
  674. .Xml
  675. [source,xml,role="secondary"]
  676. ----
  677. <http>
  678. <oauth2-login login-page="/login/oauth2"
  679. ...
  680. />
  681. </http>
  682. ----
  683. ====
  684. [IMPORTANT]
  685. You need to provide a `@Controller` with a `@RequestMapping("/login/oauth2")` that is capable of rendering the custom login page.
  686. [TIP]
  687. ====
  688. As noted earlier, configuring `oauth2Login().authorizationEndpoint().baseUri()` is optional.
  689. However, if you choose to customize it, ensure the link to each OAuth Client matches the `authorizationEndpoint().baseUri()`.
  690. The following line shows an example:
  691. [source,html]
  692. ----
  693. <a href="/login/oauth2/authorization/google">Google</a>
  694. ----
  695. ====
  696. [[oauth2login-advanced-redirection-endpoint]]
  697. === Redirection Endpoint
  698. 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.
  699. [TIP]
  700. OAuth 2.0 Login leverages the Authorization Code Grant.
  701. Therefore, the authorization credential is the authorization code.
  702. The default Authorization Response `baseUri` (redirection endpoint) is `*/login/oauth2/code/**`, which is defined in `OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI`.
  703. If you would like to customize the Authorization Response `baseUri`, configure it as shown in the following example:
  704. .Redirection Endpoint Configuration
  705. ====
  706. .Java
  707. [source,java,role="primary"]
  708. ----
  709. @EnableWebSecurity
  710. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  711. @Override
  712. protected void configure(HttpSecurity http) throws Exception {
  713. http
  714. .oauth2Login(oauth2 -> oauth2
  715. .redirectionEndpoint(redirection -> redirection
  716. .baseUri("/login/oauth2/callback/*")
  717. ...
  718. )
  719. );
  720. }
  721. }
  722. ----
  723. .Kotlin
  724. [source,kotlin,role="secondary"]
  725. ----
  726. @EnableWebSecurity
  727. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  728. override fun configure(http: HttpSecurity) {
  729. http {
  730. oauth2Login {
  731. redirectionEndpoint {
  732. baseUri = "/login/oauth2/callback/*"
  733. }
  734. }
  735. }
  736. }
  737. }
  738. ----
  739. .Xml
  740. [source,xml,role="secondary"]
  741. ----
  742. <http>
  743. <oauth2-login login-processing-url="/login/oauth2/callback/*"
  744. ...
  745. />
  746. </http>
  747. ----
  748. ====
  749. [IMPORTANT]
  750. ====
  751. You also need to ensure the `ClientRegistration.redirectUri` matches the custom Authorization Response `baseUri`.
  752. The following listing shows an example:
  753. .Java
  754. [source,java,role="primary",attrs="-attributes"]
  755. ----
  756. return CommonOAuth2Provider.GOOGLE.getBuilder("google")
  757. .clientId("google-client-id")
  758. .clientSecret("google-client-secret")
  759. .redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}")
  760. .build();
  761. ----
  762. .Kotlin
  763. [source,kotlin,role="secondary",attrs="-attributes"]
  764. ----
  765. return CommonOAuth2Provider.GOOGLE.getBuilder("google")
  766. .clientId("google-client-id")
  767. .clientSecret("google-client-secret")
  768. .redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}")
  769. .build()
  770. ----
  771. ====
  772. [[oauth2login-advanced-userinfo-endpoint]]
  773. === UserInfo Endpoint
  774. The UserInfo Endpoint includes a number of configuration options, as described in the following sub-sections:
  775. * <<oauth2login-advanced-map-authorities, Mapping User Authorities>>
  776. * <<oauth2login-advanced-oauth2-user-service, OAuth 2.0 UserService>>
  777. * <<oauth2login-advanced-oidc-user-service, OpenID Connect 1.0 UserService>>
  778. [[oauth2login-advanced-map-authorities]]
  779. ==== Mapping User Authorities
  780. 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.
  781. [TIP]
  782. `OAuth2AuthenticationToken.getAuthorities()` is used for authorizing requests, such as in `hasRole('USER')` or `hasRole('ADMIN')`.
  783. There are a couple of options to choose from when mapping user authorities:
  784. * <<oauth2login-advanced-map-authorities-grantedauthoritiesmapper, Using a GrantedAuthoritiesMapper>>
  785. * <<oauth2login-advanced-map-authorities-oauth2userservice, Delegation-based strategy with OAuth2UserService>>
  786. [[oauth2login-advanced-map-authorities-grantedauthoritiesmapper]]
  787. ===== Using a GrantedAuthoritiesMapper
  788. Provide an implementation of `GrantedAuthoritiesMapper` and configure it as shown in the following example:
  789. .Granted Authorities Mapper Configuration
  790. ====
  791. .Java
  792. [source,java,role="primary"]
  793. ----
  794. @EnableWebSecurity
  795. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  796. @Override
  797. protected void configure(HttpSecurity http) throws Exception {
  798. http
  799. .oauth2Login(oauth2 -> oauth2
  800. .userInfoEndpoint(userInfo -> userInfo
  801. .userAuthoritiesMapper(this.userAuthoritiesMapper())
  802. ...
  803. )
  804. );
  805. }
  806. private GrantedAuthoritiesMapper userAuthoritiesMapper() {
  807. return (authorities) -> {
  808. Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
  809. authorities.forEach(authority -> {
  810. if (OidcUserAuthority.class.isInstance(authority)) {
  811. OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority;
  812. OidcIdToken idToken = oidcUserAuthority.getIdToken();
  813. OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();
  814. // Map the claims found in idToken and/or userInfo
  815. // to one or more GrantedAuthority's and add it to mappedAuthorities
  816. } else if (OAuth2UserAuthority.class.isInstance(authority)) {
  817. OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority;
  818. Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();
  819. // Map the attributes found in userAttributes
  820. // to one or more GrantedAuthority's and add it to mappedAuthorities
  821. }
  822. });
  823. return mappedAuthorities;
  824. };
  825. }
  826. }
  827. ----
  828. .Kotlin
  829. [source,kotlin,role="secondary"]
  830. ----
  831. @EnableWebSecurity
  832. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  833. override fun configure(http: HttpSecurity) {
  834. http {
  835. oauth2Login {
  836. userInfoEndpoint {
  837. userAuthoritiesMapper = userAuthoritiesMapper()
  838. }
  839. }
  840. }
  841. }
  842. private fun userAuthoritiesMapper(): GrantedAuthoritiesMapper = GrantedAuthoritiesMapper { authorities: Collection<GrantedAuthority> ->
  843. val mappedAuthorities = emptySet<GrantedAuthority>()
  844. authorities.forEach { authority ->
  845. if (authority is OidcUserAuthority) {
  846. val idToken = authority.idToken
  847. val userInfo = authority.userInfo
  848. // Map the claims found in idToken and/or userInfo
  849. // to one or more GrantedAuthority's and add it to mappedAuthorities
  850. } else if (authority is OAuth2UserAuthority) {
  851. val userAttributes = authority.attributes
  852. // Map the attributes found in userAttributes
  853. // to one or more GrantedAuthority's and add it to mappedAuthorities
  854. }
  855. }
  856. mappedAuthorities
  857. }
  858. }
  859. ----
  860. .Xml
  861. [source,xml,role="secondary"]
  862. ----
  863. <http>
  864. <oauth2-login user-authorities-mapper-ref="userAuthoritiesMapper"
  865. ...
  866. />
  867. </http>
  868. ----
  869. ====
  870. Alternatively, you may register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the configuration, as shown in the following example:
  871. .Granted Authorities Mapper Bean Configuration
  872. ====
  873. .Java
  874. [source,java,role="primary"]
  875. ----
  876. @EnableWebSecurity
  877. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  878. @Override
  879. protected void configure(HttpSecurity http) throws Exception {
  880. http
  881. .oauth2Login(withDefaults());
  882. }
  883. @Bean
  884. public GrantedAuthoritiesMapper userAuthoritiesMapper() {
  885. ...
  886. }
  887. }
  888. ----
  889. .Kotlin
  890. [source,kotlin,role="secondary"]
  891. ----
  892. @EnableWebSecurity
  893. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  894. override fun configure(http: HttpSecurity) {
  895. http {
  896. oauth2Login { }
  897. }
  898. }
  899. @Bean
  900. fun userAuthoritiesMapper(): GrantedAuthoritiesMapper {
  901. ...
  902. }
  903. }
  904. ----
  905. ====
  906. [[oauth2login-advanced-map-authorities-oauth2userservice]]
  907. ===== Delegation-based strategy with OAuth2UserService
  908. 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).
  909. 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.
  910. The following example shows how to implement and configure a delegation-based strategy using an OpenID Connect 1.0 UserService:
  911. .OAuth2UserService Configuration
  912. ====
  913. .Java
  914. [source,java,role="primary"]
  915. ----
  916. @EnableWebSecurity
  917. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  918. @Override
  919. protected void configure(HttpSecurity http) throws Exception {
  920. http
  921. .oauth2Login(oauth2 -> oauth2
  922. .userInfoEndpoint(userInfo -> userInfo
  923. .oidcUserService(this.oidcUserService())
  924. ...
  925. )
  926. );
  927. }
  928. private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
  929. final OidcUserService delegate = new OidcUserService();
  930. return (userRequest) -> {
  931. // Delegate to the default implementation for loading a user
  932. OidcUser oidcUser = delegate.loadUser(userRequest);
  933. OAuth2AccessToken accessToken = userRequest.getAccessToken();
  934. Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
  935. // TODO
  936. // 1) Fetch the authority information from the protected resource using accessToken
  937. // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities
  938. // 3) Create a copy of oidcUser but use the mappedAuthorities instead
  939. oidcUser = new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());
  940. return oidcUser;
  941. };
  942. }
  943. }
  944. ----
  945. .Kotlin
  946. [source,kotlin,role="secondary"]
  947. ----
  948. @EnableWebSecurity
  949. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  950. override fun configure(http: HttpSecurity) {
  951. http {
  952. oauth2Login {
  953. userInfoEndpoint {
  954. oidcUserService = oidcUserService()
  955. }
  956. }
  957. }
  958. }
  959. @Bean
  960. fun oidcUserService(): OAuth2UserService<OidcUserRequest, OidcUser> {
  961. val delegate = OidcUserService()
  962. return OAuth2UserService { userRequest ->
  963. // Delegate to the default implementation for loading a user
  964. var oidcUser = delegate.loadUser(userRequest)
  965. val accessToken = userRequest.accessToken
  966. val mappedAuthorities = HashSet<GrantedAuthority>()
  967. // TODO
  968. // 1) Fetch the authority information from the protected resource using accessToken
  969. // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities
  970. // 3) Create a copy of oidcUser but use the mappedAuthorities instead
  971. oidcUser = DefaultOidcUser(mappedAuthorities, oidcUser.idToken, oidcUser.userInfo)
  972. oidcUser
  973. }
  974. }
  975. }
  976. ----
  977. .Xml
  978. [source,xml,role="secondary"]
  979. ----
  980. <http>
  981. <oauth2-login oidc-user-service-ref="oidcUserService"
  982. ...
  983. />
  984. </http>
  985. ----
  986. ====
  987. [[oauth2login-advanced-oauth2-user-service]]
  988. ==== OAuth 2.0 UserService
  989. `DefaultOAuth2UserService` is an implementation of an `OAuth2UserService` that supports standard OAuth 2.0 Provider's.
  990. [NOTE]
  991. `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`.
  992. `DefaultOAuth2UserService` uses a `RestOperations` when requesting the user attributes at the UserInfo Endpoint.
  993. If you need to customize the pre-processing of the UserInfo Request, you can provide `DefaultOAuth2UserService.setRequestEntityConverter()` with a custom `Converter<OAuth2UserRequest, RequestEntity<?>>`.
  994. The default implementation `OAuth2UserRequestEntityConverter` builds a `RequestEntity` representation of a UserInfo Request that sets the `OAuth2AccessToken` in the `Authorization` header by default.
  995. 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`.
  996. The default `RestOperations` is configured as follows:
  997. [source,java]
  998. ----
  999. RestTemplate restTemplate = new RestTemplate();
  1000. restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
  1001. ----
  1002. `OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error (400 Bad Request).
  1003. It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`.
  1004. Whether you customize `DefaultOAuth2UserService` or provide your own implementation of `OAuth2UserService`, you'll need to configure it as shown in the following example:
  1005. ====
  1006. .Java
  1007. [source,java,role="primary"]
  1008. ----
  1009. @EnableWebSecurity
  1010. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  1011. @Override
  1012. protected void configure(HttpSecurity http) throws Exception {
  1013. http
  1014. .oauth2Login(oauth2 -> oauth2
  1015. .userInfoEndpoint(userInfo -> userInfo
  1016. .userService(this.oauth2UserService())
  1017. ...
  1018. )
  1019. );
  1020. }
  1021. private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
  1022. ...
  1023. }
  1024. }
  1025. ----
  1026. .Kotlin
  1027. [source,kotlin,role="secondary"]
  1028. ----
  1029. @EnableWebSecurity
  1030. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  1031. override fun configure(http: HttpSecurity) {
  1032. http {
  1033. oauth2Login {
  1034. userInfoEndpoint {
  1035. userService = oauth2UserService()
  1036. // ...
  1037. }
  1038. }
  1039. }
  1040. }
  1041. private fun oauth2UserService(): OAuth2UserService<OAuth2UserRequest, OAuth2User> {
  1042. // ...
  1043. }
  1044. }
  1045. ----
  1046. ====
  1047. [[oauth2login-advanced-oidc-user-service]]
  1048. ==== OpenID Connect 1.0 UserService
  1049. `OidcUserService` is an implementation of an `OAuth2UserService` that supports OpenID Connect 1.0 Provider's.
  1050. The `OidcUserService` leverages the `DefaultOAuth2UserService` when requesting the user attributes at the UserInfo Endpoint.
  1051. 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`.
  1052. 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:
  1053. ====
  1054. .Java
  1055. [source,java,role="primary"]
  1056. ----
  1057. @EnableWebSecurity
  1058. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  1059. @Override
  1060. protected void configure(HttpSecurity http) throws Exception {
  1061. http
  1062. .oauth2Login(oauth2 -> oauth2
  1063. .userInfoEndpoint(userInfo -> userInfo
  1064. .oidcUserService(this.oidcUserService())
  1065. ...
  1066. )
  1067. );
  1068. }
  1069. private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
  1070. ...
  1071. }
  1072. }
  1073. ----
  1074. .Kotlin
  1075. [source,kotlin,role="secondary"]
  1076. ----
  1077. @EnableWebSecurity
  1078. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  1079. override fun configure(http: HttpSecurity) {
  1080. http {
  1081. oauth2Login {
  1082. userInfoEndpoint {
  1083. oidcUserService = oidcUserService()
  1084. // ...
  1085. }
  1086. }
  1087. }
  1088. }
  1089. private fun oidcUserService(): OAuth2UserService<OidcUserRequest, OidcUser> {
  1090. // ...
  1091. }
  1092. }
  1093. ----
  1094. ====
  1095. [[oauth2login-advanced-idtoken-verify]]
  1096. === ID Token Signature Verification
  1097. 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.
  1098. 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).
  1099. The `OidcIdTokenDecoderFactory` provides a `JwtDecoder` used for `OidcIdToken` signature verification. The default algorithm is `RS256` but may be different when assigned during client registration.
  1100. For these cases, a resolver may be configured to return the expected JWS algorithm assigned for a specific client.
  1101. 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`
  1102. The following code shows how to configure the `OidcIdTokenDecoderFactory` `@Bean` to default to `MacAlgorithm.HS256` for all `ClientRegistration`:
  1103. ====
  1104. .Java
  1105. [source,java,role="primary"]
  1106. ----
  1107. @Bean
  1108. public JwtDecoderFactory<ClientRegistration> idTokenDecoderFactory() {
  1109. OidcIdTokenDecoderFactory idTokenDecoderFactory = new OidcIdTokenDecoderFactory();
  1110. idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> MacAlgorithm.HS256);
  1111. return idTokenDecoderFactory;
  1112. }
  1113. ----
  1114. .Kotlin
  1115. [source,kotlin,role="secondary"]
  1116. ----
  1117. @Bean
  1118. fun idTokenDecoderFactory(): JwtDecoderFactory<ClientRegistration?> {
  1119. val idTokenDecoderFactory = OidcIdTokenDecoderFactory()
  1120. idTokenDecoderFactory.setJwsAlgorithmResolver { MacAlgorithm.HS256 }
  1121. return idTokenDecoderFactory
  1122. }
  1123. ----
  1124. ====
  1125. [NOTE]
  1126. 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.
  1127. [TIP]
  1128. 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.
  1129. [[oauth2login-advanced-oidc-logout]]
  1130. === OpenID Connect 1.0 Logout
  1131. OpenID Connect Session Management 1.0 allows the ability to log out the End-User at the Provider using the Client.
  1132. One of the strategies available is https://openid.net/specs/openid-connect-session-1_0.html#RPLogout[RP-Initiated Logout].
  1133. 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].
  1134. This can be achieved by configuring the `ClientRegistration` with the `issuer-uri`, as in the following example:
  1135. [source,yaml]
  1136. ----
  1137. spring:
  1138. security:
  1139. oauth2:
  1140. client:
  1141. registration:
  1142. okta:
  1143. client-id: okta-client-id
  1144. client-secret: okta-client-secret
  1145. ...
  1146. provider:
  1147. okta:
  1148. issuer-uri: https://dev-1234.oktapreview.com
  1149. ----
  1150. ...and the `OidcClientInitiatedLogoutSuccessHandler`, which implements RP-Initiated Logout, may be configured as follows:
  1151. ====
  1152. .Java
  1153. [source,java,role="primary"]
  1154. ----
  1155. @EnableWebSecurity
  1156. public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
  1157. @Autowired
  1158. private ClientRegistrationRepository clientRegistrationRepository;
  1159. @Override
  1160. protected void configure(HttpSecurity http) throws Exception {
  1161. http
  1162. .authorizeRequests(authorize -> authorize
  1163. .anyRequest().authenticated()
  1164. )
  1165. .oauth2Login(withDefaults())
  1166. .logout(logout -> logout
  1167. .logoutSuccessHandler(oidcLogoutSuccessHandler())
  1168. );
  1169. }
  1170. private LogoutSuccessHandler oidcLogoutSuccessHandler() {
  1171. OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler =
  1172. new OidcClientInitiatedLogoutSuccessHandler(this.clientRegistrationRepository);
  1173. // Sets the location that the End-User's User Agent will be redirected to
  1174. // after the logout has been performed at the Provider
  1175. oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");
  1176. return oidcLogoutSuccessHandler;
  1177. }
  1178. }
  1179. NOTE: `OidcClientInitiatedLogoutSuccessHandler` supports the `{baseUrl}` placeholder.
  1180. If used, the application's base URL, like `https://app.example.org`, will replace it at request time.
  1181. ----
  1182. .Kotlin
  1183. [source,kotlin,role="secondary"]
  1184. ----
  1185. @EnableWebSecurity
  1186. class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
  1187. @Autowired
  1188. private lateinit var clientRegistrationRepository: ClientRegistrationRepository
  1189. override fun configure(http: HttpSecurity) {
  1190. http {
  1191. authorizeRequests {
  1192. authorize(anyRequest, authenticated)
  1193. }
  1194. oauth2Login { }
  1195. logout {
  1196. logoutSuccessHandler = oidcLogoutSuccessHandler()
  1197. }
  1198. }
  1199. }
  1200. private fun oidcLogoutSuccessHandler(): LogoutSuccessHandler {
  1201. val oidcLogoutSuccessHandler = OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository)
  1202. // Sets the location that the End-User's User Agent will be redirected to
  1203. // after the logout has been performed at the Provider
  1204. oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}")
  1205. return oidcLogoutSuccessHandler
  1206. }
  1207. }
  1208. NOTE: `OidcClientInitiatedLogoutSuccessHandler` supports the `{baseUrl}` placeholder.
  1209. If used, the application's base URL, like `https://app.example.org`, will replace it at request time.
  1210. ----
  1211. ====