好的阿杰,我帮你整理一个完整的 Java OAuth2.0 服务端与客户端实现指南,涵盖原理、依赖、示例代码和配置方法,方便入门和实践。


🛡 Java OAuth2.0 服务端与客户端实现指南

一、OAuth2.0 基本概念

  • OAuth2.0 是一种授权协议,用于第三方应用访问用户资源而不直接暴露用户名和密码。
  • 核心角色:
    1. Resource Owner(资源所有者):用户
    2. Client(客户端):需要访问资源的应用
    3. Authorization Server(授权服务器):颁发访问令牌(Access Token)
    4. Resource Server(资源服务器):提供受保护资源
  • 核心流程:
    1. 客户端请求授权码(Authorization Code)
    2. 用授权码换取 Access Token
    3. 用 Access Token 请求资源服务器获取数据

二、服务端实现(Spring Boot + Spring Security OAuth2)

1. 添加依赖(Maven)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth.boot</groupId>
    <artifactId>spring-security-oauth2-autoconfigure</artifactId>
    <version>2.5.5</version>
</dependency>

2. 配置授权服务器

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("clientapp")
            .secret("{noop}123456")
            .authorizedGrantTypes("authorization_code","refresh_token","password")
            .scopes("read","write")
            .redirectUris("http://localhost:8081/login/oauth2/code/");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }
}

3. 配置 WebSecurity

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
          .antMatchers("/login","/oauth/authorize").permitAll()
          .anyRequest().authenticated()
          .and().formLogin();
    }
}

三、客户端实现(Spring Boot + OAuth2 Client)

1. 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

2. 配置 application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          myclient:
            client-id: clientapp
            client-secret: 123456
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope: read,write
        provider:
          myprovider:
            authorization-uri: http://localhost:8080/oauth/authorize
            token-uri: http://localhost:8080/oauth/token

3. 客户端控制器示例

@RestController
public class ClientController {

    @GetMapping("/user")
    public Map<String, Object> user(@AuthenticationPrincipal OAuth2User principal) {
        return Collections.singletonMap("name", principal.getAttribute("name"));
    }
}

四、常用授权模式

授权模式使用场景
Authorization CodeWeb 应用,安全性高
Implicit单页应用,直接获取 Token
Password Credentials信任的客户端,如企业内部应用
Client Credentials服务到服务,后台程序

五、调试与测试

  1. 启动授权服务器:http://localhost:8080/oauth/authorize
  2. 启动客户端应用:访问 /oauth2/authorization/myclient
  3. 授权后回调客户端,获取 Access Token 并访问受保护资源

💡 总结

  • OAuth2.0 授权服务器负责颁发 Token
  • 客户端通过 Token 请求资源服务器
  • Spring Boot + Spring Security OAuth2 提供完整实现框架,支持多种授权模式
  • 生产环境需注意 HTTPS、Token 有效期、刷新机制和安全存储