spring boot 第三方登录绑定(通过GitHub和Google账户)

2,067 阅读2分钟

概述

在这个教程中,我们将实现一个使用Spring Boot和Spring Security的应用程序,该应用程序允许用户通过GitHub和Google账户进行第三方登录绑定。

以下是我们将要完成的主要步骤:

  1. 创建一个Spring Boot项目
  2. 配置Spring Security
  3. 配置第三方登录提供商(如GitHub和Google)
  4. 创建登录和注册页面
  5. 实现用户服务和用户细节服务
  6. 实现OAuth2登录成功处理器

步骤1:创建一个Spring Boot项目

首先,我们需要创建一个Spring Boot项目。您可以使用Spring Initializr来生成一个新的项目。在依赖项中添加spring-boot-starter-web, spring-boot-starter-security, spring-boot-starter-oauth2-client, spring-boot-starter-data-jpah2(一个内存数据库)。

步骤2:配置Spring Security

创建一个名为SecurityConfig的配置类,并扩展WebSecurityConfigurerAdapter。在此类中,我们将配置Spring Security以使用OAuth2登录和自定义的登录成功处理器。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private OAuth2LoginSuccessHandler oAuth2LoginSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/", "/login**", "/webjars/**", "/error**")
                .permitAll()
            .anyRequest()
                .authenticated()
            .and()
            .oauth2Login()
                .loginPage("/login")
                .defaultSuccessURL("/dashboard")
                .successHandler(oAuth2LoginSuccessHandler);
    }
}

步骤3:配置第三方登录提供商

application.properties文件中,我们需要配置GitHub和Google作为第三方登录提供商。

spring.security.oauth2.client.registration.github.client-id=<your_github_client_id>
spring.security.oauth2.client.registration.github.client-secret=<your_github_client_secret>
spring.security.oauth2.client.registration.github.scope=read:user

spring.security.oauth2.client.registration.google.client-id=<your_google_client_id>
spring.security.oauth2.client.registration.google.client-secret=<your_google_client_secret>
spring.security.oauth2.client.registration.google.scope=openid,profile,email

步骤4:创建登录和注册页面

创建一个名为login.html的登录页面,并在其中添加GitHub和Google登录按钮。这些按钮将指向Spring Security为我们生成的OAuth2授权URL。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <div>
        <a href="/oauth2/authorization/github">Login with GitHub</a>
    </div>
    <div>
        <a href="/oauth2/authorization/google">Login with Google</a>
    </div>
</body>
</html>

步骤5:实现用户服务和用户细节服务

创建一个名为UserService的服务类,并实现UserDetailsService接口。在这个类中,我们将实现逻辑来处理从第三方登录提供商收到的用户信息,并将其存储在我们的数据库中。

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // ...
    }

    public User saveOrUpdateUser(User user) {
        // ...
    }

    public User findUserByEmail(String email) {
        // ...
    }
}

步骤6:实现OAuth2登录成功处理器

创建一个名为OAuth2LoginSuccessHandler的类,并实现AuthenticationSuccessHandler接口。在这个类中,我们将处理OAuth2登录成功事件,并将用户信息传递给UserService以进行存储。

@Component
public class OAuth2LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal();
        String email = oAuth2User.getAttribute("email");
        User user = userService.findUserByEmail(email);

        if (user == null) {
            user = new User();
            user.setEmail(email);
            user.setName(oAuth2User.getAttribute("name"));
            user.setProvider(Provider.valueOf(oAuth2User.getAttribute("provider")));
        }

        userService.saveOrUpdateUser(user);
        // Redirect to the default success URL (e.g., /dashboard)
        response.sendRedirect("/");
    }
}

这仅是实现Spring Boot项目的第三方登录绑定的概述和关键代码片段。您可以根据这些信息来实现您自己的项目。要获得更详细的信息和代码,请参阅相关文档和教程。