how-to-social-login.adoc 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. [[how-to-social-login]]
  2. = How-to: Authenticate using Social Login
  3. :index-link: ../how-to.html
  4. :docs-dir: ..
  5. :examples-dir: {docs-dir}/examples
  6. :samples-dir: {docs-dir}/../../../../samples
  7. :github-ref: main
  8. :github-base-url: https://github.com/spring-projects/spring-authorization-server/blob/{github-ref}
  9. This guide shows how to configure xref:{docs-dir}/index.adoc#top[Spring Authorization Server] with a social login provider (such as Google, GitHub, etc.) for {spring-security-reference-base-url}/servlet/authentication/index.html[authentication].
  10. The purpose of this guide is to demonstrate how to replace {spring-security-reference-base-url}/servlet/authentication/passwords/form.html[Form Login] with {spring-security-reference-base-url}/servlet/oauth2/login/index.html[OAuth 2.0 Login].
  11. NOTE: Spring Authorization Server is built on {spring-security-reference-base-url}/index.html[Spring Security] and we will be using Spring Security concepts throughout this guide.
  12. * <<register-social-login-provider>>
  13. * <<configure-oauth2-login>>
  14. * <<advanced-use-cases>>
  15. [[register-social-login-provider]]
  16. == Register with Social Login Provider
  17. To get started, you will need to set up an application with your chosen social login provider.
  18. Common providers include:
  19. * https://developers.google.com/identity/openid-connect/openid-connect#appsetup[Google]
  20. * https://github.com/settings/developers[GitHub]
  21. * https://developers.facebook.com/apps[Facebook]
  22. * https://www.okta.com/developer/signup[Okta]
  23. Follow the steps for your provider until you are asked to specify a Redirect URI.
  24. To set up a Redirect URI, choose a `registrationId` (such as `google`, `my-client` or any other unique identifier you wish) which you will use to configure both Spring Security **and** your provider.
  25. NOTE: The `registrationId` is a unique identifier for the `ClientRegistration` in Spring Security. The default Redirect URI template is `\{baseUrl\}/login/oauth2/code/\{registrationId\}`. See {spring-security-reference-base-url}/servlet/oauth2/login/core.html#oauth2login-sample-redirect-uri[Setting the Redirect URI] in the Spring Security reference for more information.
  26. TIP: For example, testing locally on port `9000` with a `registrationId` of `google`, your Redirect URI would be `http://localhost:9000/login/oauth2/code/google`. Enter this value as the Redirect URI when setting up the application with your provider.
  27. Once you've completed the set-up process with your social login provider, you should have obtained credentials (a Client ID and Client Secret).
  28. In addition, you will need to reference the provider's documentation and take note of the following values:
  29. * **Authorization URI**: The endpoint that is used to initiate the `authorization_code` flow at the provider.
  30. * **Token URI**: The endpoint that is used to exchange an `authorization_code` for an `access_token` and optionally an `id_token`.
  31. * **JWK Set URI**: The endpoint that is used to obtain keys for verifying the signature of a JWT, which is required when an `id_token` is available.
  32. * **User Info URI**: The endpoint that is used to obtain user information, which is required when an `id_token` is not available.
  33. * **User Name Attribute**: The claim in either the `id_token` or the User Info Response containing the username of the user.
  34. [[configure-oauth2-login]]
  35. == Configure OAuth 2.0 Login
  36. Once you've <<register-social-login-provider,registered>> with a social login provider, you can proceed to configuring Spring Security for {spring-security-reference-base-url}/servlet/oauth2/login/index.html[OAuth 2.0 Login].
  37. * <<configure-oauth2-login-dependency>>
  38. * <<configure-oauth2-login-client-registration>>
  39. * <<configure-oauth2-login-authentication>>
  40. [[configure-oauth2-login-dependency]]
  41. === Add OAuth2 Client Dependency
  42. First, add the following dependency:
  43. [[configure-oauth2-login-maven-dependency]]
  44. .Maven
  45. [source,xml,role="primary",subs="attributes,verbatim"]
  46. ----
  47. <dependency>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-starter-oauth2-client</artifactId>
  50. </dependency>
  51. ----
  52. [[configure-oauth2-login-gradle-dependency]]
  53. .Gradle
  54. [source,gradle,role="secondary",subs="attributes,verbatim"]
  55. ----
  56. implementation "org.springframework.boot:spring-boot-starter-oauth2-client"
  57. ----
  58. [[configure-oauth2-login-client-registration]]
  59. === Register a Client
  60. Next, configure the `ClientRegistration` with the values obtained <<register-social-login-provider,earlier>>.
  61. Using Okta as an example, configure the following properties:
  62. [[configure-oauth2-login-okta-example]]
  63. .application.yml
  64. [source,yaml]
  65. ----
  66. include::{examples-dir}/src/main/java/sample/socialLogin/application.yml[]
  67. ----
  68. NOTE: The `registrationId` in the above example is `my-client`.
  69. TIP: The above example demonstrates the *recommended* way to set the Provider URL, Client ID and Client Secret using environment variables (`OKTA_BASE_URL`, `OKTA_CLIENT_ID` and `OKTA_CLIENT_SECRET`). See {spring-boot-reference-base-url}/features.html#features.external-config[Externalized Configuration] in the Spring Boot reference for more information.
  70. This simple example demonstrates a typical configuration, but some providers will require additional configuration.
  71. For more information about configuring the `ClientRegistration`, see {spring-security-reference-base-url}/servlet/oauth2/login/core.html#oauth2login-boot-property-mappings[Spring Boot Property Mappings] in the Spring Security reference.
  72. [[configure-oauth2-login-authentication]]
  73. === Configure Authentication
  74. Finally, to configure Spring Authorization Server to use a social login provider for authentication, you can use `oauth2Login()` instead of `formLogin()`.
  75. You can also automatically redirect an unauthenticated user to the provider by configuring `exceptionHandling()` with an `AuthenticationEntryPoint`.
  76. Continuing our <<configure-oauth2-login-okta-example,earlier example>>, configure Spring Security using a `@Configuration` as in the following example:
  77. .Configure OAuth 2.0 Login
  78. [source,java]
  79. ----
  80. include::{examples-dir}/src/main/java/sample/socialLogin/SecurityConfig.java[]
  81. ----
  82. <1> A Spring Security filter chain for the xref:{docs-dir}/protocol-endpoints.adoc[Protocol Endpoints].
  83. <2> Configure an `AuthenticationEntryPoint` for redirecting to the {spring-security-reference-base-url}/servlet/oauth2/login/advanced.html#oauth2login-advanced-login-page[OAuth 2.0 Login endpoint].
  84. <3> A Spring Security filter chain for https://docs.spring.io/spring-security/reference/servlet/authentication/index.html[authentication].
  85. <4> Configure {spring-security-reference-base-url}/servlet/oauth2/login/index.html[OAuth 2.0 Login] for authentication.
  86. If you configured a `UserDetailsService` when xref:{docs-dir}/getting-started.adoc#developing-your-first-application[getting started], you can remove it now.
  87. [[advanced-use-cases]]
  88. == Advanced Use Cases
  89. The https://github.com/spring-projects/spring-authorization-server/tree/{github-ref}/samples#demo-sample[demo authorization server sample^] demonstrates advanced configuration options for federating identity providers.
  90. Select from the following use cases to see an example of each:
  91. * I want to <<advanced-use-cases-capture-users>>
  92. * I want to <<advanced-use-cases-map-claims>>
  93. [[advanced-use-cases-capture-users]]
  94. === Capture Users in a Database
  95. The following example `AuthenticationSuccessHandler` uses a custom component to capture users in a local database when they first log in:
  96. .`FederatedIdentityAuthenticationSuccessHandler`
  97. [source,java]
  98. ----
  99. include::{samples-dir}/demo-authorizationserver/src/main/java/sample/federation/FederatedIdentityAuthenticationSuccessHandler.java[tags=imports;class]
  100. ----
  101. Using the `AuthenticationSuccessHandler` above, you can plug in your own `Consumer<OAuth2User>` that can capture users in a database or other data store for concepts like Federated Account Linking or JIT Account Provisioning.
  102. Here is an example that simply stores users in-memory:
  103. .`UserRepositoryOAuth2UserHandler`
  104. [source,java]
  105. ----
  106. include::{samples-dir}/demo-authorizationserver/src/main/java/sample/federation/UserRepositoryOAuth2UserHandler.java[tags=imports;class]
  107. ----
  108. [[advanced-use-cases-map-claims]]
  109. === Map Claims to an ID Token
  110. The following example `OAuth2TokenCustomizer` maps a user's claims from an authentication provider to the `id_token` produced by Spring Authorization Server:
  111. .`FederatedIdentityIdTokenCustomizer`
  112. [source,java]
  113. ----
  114. include::{samples-dir}/demo-authorizationserver/src/main/java/sample/federation/FederatedIdentityIdTokenCustomizer.java[tags=imports;class]
  115. ----
  116. You can configure Spring Authorization Server to use this customizer by publishing it as a `@Bean` as in the following example:
  117. .Configure `FederatedIdentityIdTokenCustomizer`
  118. [source,java]
  119. ----
  120. @Bean
  121. public OAuth2TokenCustomizer<JwtEncodingContext> idTokenCustomizer() {
  122. return new FederatedIdentityIdTokenCustomizer();
  123. }
  124. ----