Java 后端 / 知识点

Spring Cloud 微服务速查手册

手册条目

为内部调用配置客户端凭证或双向 TLS 身份认证。

校验服务间身份

用于阻止未授权服务伪造内部调用。常见做法是 OAuth 2.0 客户端凭证颁发短期访问令牌,或用双向 TLS 在握手阶段校验证书。需要细粒度授权时优先令牌;强调网络层身份和证书绑定时优先 mTLS;高敏链路可叠加使用。

服务间身份校验流程

方案选择

客户端凭证适合“服务身份 + 接口权限”场景,令牌可携带 scope、aud 等声明,并能短期失效。mTLS 适合零信任网络、合规链路或网关到后端的强身份绑定,但证书签发、分发和轮换成本更高。两者叠加时,mTLS 证明连接方身份,令牌负责业务授权。

配置客户端凭证

以下配置假设调用方同时需要访问受保护接口,并使用 Spring Security OAuth2 Client 自动获取令牌。客户端密钥只从环境变量或密钥管理系统注入,不写入仓库。

yaml
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: ${OIDC_ISSUER_URI}
      client:
        registration:
          inventory:
            provider: internal-idp
            client-id: ${INVENTORY_CLIENT_ID}
            client-secret: ${INVENTORY_CLIENT_SECRET}
            authorization-grant-type: client_credentials
            scope: inventory.read
        provider:
          internal-idp:
            token-uri: ${OIDC_TOKEN_URI}

调用请求必须统一经过带 OAuth2 过滤器的 WebClient,避免业务代码手工拼接和缓存令牌。

java
package com.example.security;

import static org.springframework.security.config.Customizer.withDefaults;

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.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class ServiceIdentityConfig {

    @Bean
    SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health").permitAll()
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()))
            .build();
    }

    @Bean
    OAuth2AuthorizedClientManager authorizedClientManager(
            ClientRegistrationRepository registrations,
            OAuth2AuthorizedClientService clients) {
        var provider = OAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build();
        var manager =
            new AuthorizedClientServiceOAuth2AuthorizedClientManager(registrations, clients);
        manager.setAuthorizedClientProvider(provider);
        return manager;
    }

    @Bean
    WebClient inventoryWebClient(OAuth2AuthorizedClientManager manager) {
        var oauth2 = new ServletOAuth2AuthorizedClientExchangeFilterFunction(manager);
        oauth2.setDefaultClientRegistrationId("inventory");
        return WebClient.builder()
            .apply(oauth2.oauth2Configuration())
            .build();
    }
}

验证令牌端点和目标服务时只输出状态码,避免把访问令牌写进终端历史或 CI 日志。

bash
TOKEN="$(curl -fsS \
  -u "${INVENTORY_CLIENT_ID}:${INVENTORY_CLIENT_SECRET}" \
  -d grant_type=client_credentials \
  -d scope=inventory.read \
  "${OIDC_TOKEN_URI}" | jq -r '.access_token')"

curl -sS -o /dev/null -w '%{http_code}\n' \
  -H "Authorization: Bearer ${TOKEN}" \
  https://inventory.internal/api/stocks/SKU-100

预期输出

text
200

401 通常表示令牌缺失、过期、签名或 issuer 校验失败;403 表示身份已通过但缺少目标接口要求的权限。

配置双向 TLS

目标服务要求客户端证书时,将受信任客户端 CA 放入 truststore,并把 client-auth 设为 need。以下为服务端配置片段,证书文件应由内部 PKI 管理。

yaml
server:
  ssl:
    enabled: true
    key-store: file:${SERVER_KEYSTORE}
    key-store-password: ${SERVER_KEYSTORE_PASSWORD}
    trust-store: file:${SERVER_TRUSTSTORE}
    trust-store-password: ${SERVER_TRUSTSTORE_PASSWORD}
    client-auth: need

使用客户端证书验证握手和接口可达性:

bash
curl --cert client.crt \
  --key client.key \
  --cacert ca.crt \
  -sS -o /dev/null -w '%{http_code}\n' \
  https://orders.internal/actuator/health

预期输出

text
200

未携带证书、证书过期、SAN 不匹配或 CA 不受信任时,请求会在 HTTP 之前失败,通常表现为 TLS handshake error,而不是 401。

风险与排障

禁止在配置文件、镜像层、命令行参数或日志中暴露 client-secret、私钥和访问令牌;安全替代方案是使用 Vault、Kubernetes Secret、云密钥服务或受控环境变量。证书轮换应保留新旧 CA 的短暂重叠窗口,否则会造成批量握手失败。

排查时按层次确认:先验证 DNS、时间同步和 TLS 握手,再检查令牌的 iss、aud、过期时间与 scope,最后核对目标服务的授权规则。mTLS 只证明证书身份,不等于自动获得接口权限,仍应将证书 SAN 或 Subject 映射为服务主体并执行授权。

兼容性

示例面向 Spring Boot 3.x 与 Spring Security 6。Spring Boot 2.x 使用 javax.servlet 生态且部分 OAuth2 配置 API 不同;升级时应按当前依赖版本调整导入包和安全配置写法。

目录与阅读设置

记录一个想法

Spring Cloud 微服务速查手册

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通