0Pricing
Spring Security 6 & JWT Authentication · 课时

社交登录集成

使用 Spring Security 的 OAuth2 客户端,将常用的社交登录提供程序(例如 Google、GitHub)集成到您的应用中。

社交登录集成 是 CoddyKit 上的免费 Spring Security 6 & JWT Authentication 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Security 6 & JWT Authentication 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Security 6 & JWT Authentication 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Social Login: Easy Access

Welcome to social login! Ever seen buttons like "Sign in with Google" or "Login with GitHub"? That's social login in action.

It lets users sign into your application using their existing accounts from popular identity providers. This means less friction for users and no new passwords to remember!

Spring Security Simplifies It

Integrating social login manually can be tricky, involving many redirects and token exchanges. But don't worry!

Spring Security provides powerful, out-of-the-box support for OAuth2 clients. It handles most of the complex flow for you, making it straightforward to add providers like Google, GitHub, or Facebook.

Your App as an OAuth2 Client

In the context of social login, your application acts as an OAuth2 Client. This client needs to be registered with the social identity provider (which is the Authorization Server).

This registration process gives your application unique credentials: a Client ID and a Client Secret.

Registering with Google (Part 1)

Let's use Google as a practical example. To enable Google Sign-In, you first need to register your application with the Google Cloud Console.

  • Create a new project.
  • Go to APIs & Services > OAuth consent screen to configure user-facing information.

This tells Google who your app is and what it wants to do.

Registering with Google (Part 2)

Next, you'll create OAuth client ID credentials. Choose 'Web application' as the application type.

The most crucial step is setting the 'Authorized redirect URIs'. This is where Google will send the user back after successful authentication.

  • For local development, this is often http://localhost:8080/login/oauth2/code/google.
  • You'll get a Client ID and Client Secret – keep these safe!

Spring Boot Configuration

With your Google Client ID and Secret, you can now configure your Spring Boot application's application.properties (or .yml) file.

Spring Security uses a convention for naming these properties. Just replace the placeholder values with your actual credentials.

spring.security.oauth2.client.registration.google.client-id=YOUR_GOOGLE_CLIENT_ID
spring.security.oauth2.client.registration.google.client-secret=YOUR_GOOGLE_CLIENT_SECRET

Minimal Security Configuration

To enable OAuth2 social login, you need a basic Spring Security configuration. Spring Boot's defaults are very helpful here.

By simply calling .oauth2Login() on your HttpSecurity object, Spring Security automatically configures the necessary filters and endpoints to handle the OAuth2 flow.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
      .authorizeHttpRequests(authorize -> authorize
        .anyRequest().authenticated() // Require authentication for all requests
      )
      .oauth2Login(oauth2 -> oauth2
        // Spring Security provides a default login page with social login links
      );
    return http.build();
  }
}

The Social Login Page

With the configuration in place, Spring Security will automatically generate a login page at /login (if no custom login page is specified).

This page will include links for each configured social provider. When a user clicks, they are redirected to the provider for authentication.

<p>Conceptual HTML for a login link:</p>
<code>&lt;a href="/oauth2/authorization/google"&gt;Login with Google&lt;/a&gt;</code>
<p>Spring Security handles the redirection to Google and processes the response.</p>

Accessing User Details

After a successful social login, Spring Security populates the SecurityContext with the authenticated user's details.

You can inject an OAuth2User object into your controllers to access information like the user's name, email, or other attributes provided by the social identity provider.

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

// This is a snippet of a Spring Boot controller.
// It needs a full Spring Boot application context to run.
@RestController
public class UserController {

  @GetMapping("/user-info")
  public String getUserInfo(@AuthenticationPrincipal OAuth2User oauth2User) {
    if (oauth2User != null) {
      String name = oauth2User.getAttribute("name");
      String email = oauth2User.getAttribute("email");
      return "Hello, " + name + "! Your email is " + email + ".";
    }
    return "User not authenticated via social login.";
  }
}

Social Login Quiz

You've learned how to set up social login! Let's test your understanding of the core components.

Social Login Recap

Great job! You've learned how to integrate social login into your Spring Boot application using Spring Security's OAuth2 client support.

  • We understood the benefits of social login and Spring Security's role.
  • We walked through setting up your app as an OAuth2 Client and registering it with a provider like Google.
  • You saw how to configure application.properties and enable .oauth2Login() in your security chain.
  • Finally, you learned how to access authenticated user details using the OAuth2User object.

Social login significantly enhances user experience and simplifies authentication!

常见问题解答

「社交登录集成」课时是免费的吗?

是的 — 「社交登录集成」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Security 6 & JWT Authentication 课程的其余内容,请升级到 CoddyKit PRO。 Spring Security 6 & JWT Authentication 课程共包含 4 节课。

「社交登录集成」这节课中我会学到什么?

使用 Spring Security 的 OAuth2 客户端,将常用的社交登录提供程序(例如 Google、GitHub)集成到您的应用中。 你通过在浏览器中直接运行的动手代码来练习 Spring Security 6 & JWT Authentication,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Security 6 & JWT Authentication 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Security 6 & JWT Authentication 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「社交登录集成」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Spring Security 6 & JWT Authentication 课中编写并运行代码吗?

能。每节 Spring Security 6 & JWT Authentication 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. OAuth2 客户端设置
  2. 社交登录集成
  3. 自定义 OAuth2 成功处理程序
  4. 访问已验证身份的 OAuth2 用户
← 返回 Spring Security 6 & JWT Authentication