You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

整合Spring Security与grpc-spring-boot-starter遇AuthenticationManager缺失

使用OpenAPI生成Spring WebClient客户端遇到的gRPC安全配置问题

背景

我用OpenAPI生成了基于Spring WebClient的Java客户端,其中提供了MergedApi类,配置了对应的Bean:

@Bean
public MergedApi mergedApi(final ApiClient apiClient) {
  return new MergedApi(apiClient);
}

为给ApiClient添加令牌支持,引入以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>${spring-boot-starter-security.version}</version>
</dependency>

因Spring Boot未提供全部所需类,额外引入:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-client</artifactId>
    <version>${spring-security-oauth2-client.version}</version>
</dependency>

用于支持Spring Boot调用REST端点的依赖:

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

同时引入gRPC相关依赖:

<dependency>
    <groupId>io.github.lognet</groupId>
    <artifactId>grpc-spring-boot-starter</artifactId>
    <version>${spring-boot-grpc-starter.version}</version>
    <scope>compile</scope>
</dependency>

启动错误

启动应用时抛出如下错误:

Error creating bean with name 'springGrpcSecurityInterceptor' defined in class path resource [org/lognet/springboot/grpc/security/GrpcSecurityConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: An AuthenticationManager is required

问题分析

调试后发现问题出在org.lognet.springboot.grpc.security.GrpcSecurityConfigurerAdapter的配置代码中:

@Override
public void configure(GrpcSecurity builder) throws Exception {
  try {
    final Class<?> jwtDecoderClass =
        Class.forName("org.springframework.security.oauth2.jwt.JwtDecoder");
    final String[] beanNames = context.getBeanNamesForType(jwtDecoderClass);
    if (1 == beanNames.length) {
      builder.authenticationProvider(
          JwtAuthProviderFactory.forAuthorities(context.getBean(beanNames[0], JwtDecoder.class)));
    }
  } catch (ClassNotFoundException e) {
  }
  // swallow
  builder.authorizeRequests().withSecuredAnnotation();
}

这段逻辑会尝试查找JwtDecoder类型的Bean,找到则添加对应认证提供者;找不到(或类不存在)时,catch块直接吞掉异常,后续执行builder.authorizeRequests().withSecuredAnnotation()时,因未配置任何认证提供者,导致AuthenticationManager缺失,最终触发错误。

已做处理

我手动添加了JwtDecoder Bean及对应依赖:

@Bean
public JwtDecoder decoder() {
    return token -> Jwt.withTokenValue(token).build();
}
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    <version>${spring-boot-starter-security.version}</version>
</dependency>

疑问

  • 是否还缺少其他依赖?
  • 这个问题的根本原因是什么?
  • 为什么gRPC安全配置这里需要JwtDecoder?
  • 有没有关于使用OpenAPI生成Java客户端的优质教程?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:09:55