You need to enable JavaScript to run this app. Spring Boot Security 同资源配置API Key或OAuth2资源服务器的认证方案
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot Security 同资源配置API Key或OAuth2资源服务器的认证方案

Spring WebFlux 双鉴权通道(API Key优先+OAuth2兜底)实现方案

核心实现原则

不需要改动现有OAuth2资源服务器的已有配置,仅需将自定义API Key认证逻辑插入到过滤器链的靠前位置,完全匹配两类校验规则:

  • API Key校验通过时,直接写入认证上下文,跳过后续所有OAuth2校验流程
  • API Key缺失、校验不通过时,不中断请求流转,让请求自然进入原有OAuth2资源服务器的认证逻辑

分步实现

1. 定义API Key认证实体

遵循Spring Security的认证Token规范,构造可被安全链路识别的API Key认证对象:

class ApiKeyAuthenticationToken(
    private val apiKey: String,
    authorities: Collection<GrantedAuthority> = emptyList()
) : AbstractAuthenticationToken(authorities) {
    // 凭证值为请求携带的API Key
    override fun getCredentials(): Any = apiKey
    // 认证主体为API Key对应的服务身份标识
    override fun getPrincipal(): Any = "service_${apiKey.takeLast(4)}"
}

2. 实现API Key请求提取逻辑

负责从请求头中解析携带的API Key,未携带API Key时直接放行,不拦截请求:

class ApiKeyServerAuthenticationConverter : ServerAuthenticationConverter {
    override fun convert(exchange: ServerWebExchange): Mono<Authentication> {
        // 从自定义请求头X-API-Key提取密钥,可根据实际场景修改头名称
        val apiKey = exchange.request.headers.getFirst("X-API-Key") 
            ?: return Mono.empty()
        return Mono.just(ApiKeyAuthenticationToken(apiKey))
    }
}

3. 实现API Key合法性校验

对应的认证管理器负责校验提取到的API Key是否在合法列表内,校验不通过时不抛出认证异常,仅返回空结果,避免中断后续过滤器链:

class ApiKeyAuthenticationManager : ReactiveAuthenticationManager {
    // 替换为实际的校验逻辑,比如匹配数据库存储的合法Key、远程调用校验接口
    private val validApiKeys = setOf("machine-call-key-001", "internal-service-key-002")

    override fun authenticate(authentication: Authentication): Mono<Authentication> {
        val apiKey = authentication.credentials as String
        // 校验通过时返回已认证的Token,设置对应权限
        if (apiKey in validApiKeys) {
            val authenticatedToken = ApiKeyAuthenticationToken(
                apiKey = apiKey,
                authorities = listOf(SimpleGrantedAuthority("MACHINE_CALL"))
            ).apply { isAuthenticated = true }
            return Mono.just(authenticatedToken)
        }
        // 校验不通过直接返回空,不中断流程,请求将继续流转到OAuth2认证环节
        return Mono.empty()
    }
}

4. 过滤器集成到原有安全配置

将自定义API Key过滤器插入到OAuth2资源服务器过滤器的前面位置,保留原有OAuth2配置完全不变:

@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? =
    http {
        // 原有授权规则保持不变
        authorizeExchange {
            authorize(anyExchange, authenticated)
        }

        // 构造API Key认证过滤器
        val apiKeyAuthFilter = AuthenticationWebFilter(ApiKeyAuthenticationManager()).apply {
            setServerAuthenticationConverter(ApiKeyServerAuthenticationConverter())
            // 覆盖默认的认证失败处理逻辑:不直接返回401,清空当前上下文后继续流转
            setReactiveAuthenticationFailureHandler { exchange, _ ->
                exchange.contextWrite(SecurityContext.empty())
                    .then(Mono.empty())
            }
        }
        // 将API Key过滤器放在OAuth2资源服务器过滤器之前执行
        addFilterBefore(apiKeyAuthFilter, SecurityWebFiltersOrder.OAUTH2_RESOURCE_SERVER)

        // 原有OAuth2资源服务器配置完全保留,无修改
        oauth2ResourceServer {
            authenticationManagerResolver(myMultiTenantResolver)
        }
    }

链路执行流程验证

配置完成后,所有请求的鉴权流转完全符合预期:

  1. 请求进入API Key校验环节
    • 未携带API Key:直接放行,进入OAuth2认证流程
    • 携带合法API Key:校验通过后写入已认证的SecurityContext,后续OAuth2过滤器检测到已有认证信息时直接跳过,完成鉴权
    • 携带非法API Key:不写入认证上下文,直接放行进入OAuth2认证流程
  2. 请求进入原有OAuth2资源服务器环节:若检测到SecurityContext中已有合法认证信息则直接通过;若没有,则按照原有逻辑解析不透明令牌完成多租户校验

内容的提问来源于stack exchange,提问作者stevietheTV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.24 03:36:09