For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt, and this page is available as Markdown at /docs/project/microservice/auth/oauth2.md.
  • 简体中文
  • 2026
  • OAuth2

    原理

    OAuth2 包含 3 个角色:

    • 客户端(client)。
    • 授权服务器(authorization-server)。例如 keycloak,鉴权、颁发 token
    • 资源服务器(resource-server)。提供接口服务,如获取用户下的图片列表,接口即为资源,需对 client 调用时携带的 token 进行校验,通过鉴权后返回数据。

    以常见的前后端模式为例,这里引入了 keycloak 作为独立的 SSO 和鉴权服务:

    客户端(Client)

    # application.yml (photo-client)
    server:
      port: 8081
    
    spring:
      security:
        oauth2:
          client:
            registration:
              photo-print:
                # 与授权服务器中定义的凭证保持一致
                client-id: "photo-client"
                client-secret: "secret"
                authorization-grant-type: "authorization_code"
                scope: "read.photos"
            provider:
              keycloak:
                # 指向授权服务器的 Issuer 地址
                issuer-uri: "http://keycloak:9000"

    需要确保客户端引入 pom 依赖:

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

    授权服务器(Authorization Server)

    可以使用开源产品如 keycloak 等支持 OAuth2 / OIDC 的产品,也可以使用 spring oauth2 authorization server 实现,示例如下:

    # application.yml (auth-server)
    server:
      port: 9000
    
    spring:
      security:
        oauth2:
          authorizationserver:
            client:
              photo-print-client:
                # 冲印服务的凭证
                client-id: "photo-client"
                client-secret: "{noop}secret"
                # 允许的授权模式:授权码模式(适合有用户参与的流程)
                authorization-grant-types:
                  - "authorization_code"
                  - "refresh_token"
                # 冲印服务登录后的回调地址
                redirect-uris:
                  - "http://localhost:8081/login/oauth2/code/photo-client"
                # 允许申请的权限范围
                scopes:
                  - "read.photos"

    需要确保授权服务器引入 pom 依赖:

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

    资源服务器(Resource Server)

    keycloak 服务可达情况下,只需配置 issuer-uri,可自动获取 jwks_uri 自动配置 JwtDecoder 来验签:

    spring:
      security:
        oauth2:
          resourceserver:
            jwt:
              issuer-uri: http://keycloak:9000/realms/your-realm

    需要启用资源服务器:

    // SecurityConfig.java (photo-api)
    @Configuration
    @EnableWebSecurity
    public class ResourceServerConfig {
    
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http
                .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/api/photos/**").hasAuthority("SCOPE_read.photos")
                    .anyRequest().authenticated()
                )
              	// 启用资源服务器
                .oauth2ResourceServer(oauth2 -> oauth2
                    .jwt(Customizer.withDefaults()) // 启用 JWT 验证
                );
            return http.build();
        }
    }

    需要确保资源服务器引入 pom 依赖:

    <!-- oauth2-resource-server -->
    <!-- JWT encoding/decoding (Nimbus) + bearer token authentication -->
    <!-- 包含 spring-security-oauth2-jose -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>

    实践

    客户端(Client)和资源服务器(Resource Server)

    现实中存在情况不会将 Client 和 Resource Server 分开的情况,会把功能同时组织到一个后端服务(spring boot)中:

    todo

    客户端(Client)和授权服务器(Authorization Server)

    todo

    参考链接

    开源项目

    文章