Spring Boot 集成 OAuth2:从入门到实战指南
在 Spring Boot 中集成 OAuth2 可以通过以下步骤实现,具体实现方式取决于你的需求,例如是否需要自定义授权服务器,或者是否作为资源服务器或客户端集成 OAuth2。
1. 创建 Spring Boot 项目
使用 Spring Initializr 创建一个新的 Spring Boot 项目,并添加以下依赖:
- 
Spring Web
 - 
Spring Security
 - 
OAuth2 Authorization Server(如果需要自定义授权服务器)
 - 
OAuth2 Resource Server(如果需要保护资源)
 - 
OAuth2 Client(如果需要作为客户端集成)
 
2. 配置 OAuth2 客户端
如果需要集成第三方 OAuth2 提供商(如 Google、GitHub 等),可以在 application.yml 文件中配置客户端信息:
spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: your-client-id
            client-secret: your-client-secret
            redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
            authorization-grant-type: authorization_code
            scope: profile, email
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
            user-name-attribute: sub
3. 配置 OAuth2 授权服务器
如果需要自定义授权服务器,可以添加 spring-boot-starter-oauth2-authorization-server 依赖,并创建一个配置类:
@Configuration
public class AuthorizationServerConfig {
    @Bean
    SecurityFilterChain authorizationServerFilterChain(HttpSecurity http) throws Exception {
        http.with(OAuth2AuthorizationServerConfigurer.authorizationServer(), Customizer.withDefaults());
        return http.build();
    }
}
4. 配置资源服务器
如果需要保护资源,可以使用 JWT 配置资源服务器:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/", "/home").permitAll()
            .anyRequest().authenticated()
            .and()
            .oauth2ResourceServer()
            .jwt();
    }
}
5. 测试 OAuth2 集成
启动应用后,访问登录页面,系统会重定向到 OAuth2 提供商的登录页面。用户登录并授权后,会被重定向回应用。
6. 高级配置
- 
多租户支持:可以配置多个 OAuth2 提供商。
 - 
令牌撤销:可以实现令牌撤销功能,用于注销用户。
 
注意事项
- 
确保客户端 ID 和密钥正确无误。
 - 
确保重定向 URI 与 OAuth2 提供商配置一致。
 
                    
                
                
            
        
浙公网安备 33010602011771号