Azure AD令牌认证授权端点时出现NoClassDefFoundError问题
排查Spring Security中
BearerTokenResolver类找不到的问题 问题场景
通过Azure AD令牌对部分端点/控制器进行认证授权,安全配置代码如下:
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Autowired private TokenFilter tokenFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() .authorizeRequests() .antMatchers( "/api/authenticate/username") .permitAll().anyRequest().authenticated().and() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler) .and() .oauth2ResourceServer() .jwt() .jwtAuthenticationConverter(new AADJwtBearerTokenAuthenticationConverter()); } }
出现编译错误,错误信息:
Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/security/oauth2/server/resource/web/BearerTokenResolver
问题原因及解决方案
- 依赖缺失:
BearerTokenResolver属于Spring Security OAuth2 Resource Server模块,项目中缺少对应的依赖包。 - 版本不匹配:若已引入依赖,可能是Spring Security核心组件与OAuth2 Resource Server版本不一致,导致类加载失败。
具体解决步骤
- Maven项目添加依赖:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-resource-server</artifactId> <!-- 版本需与spring-security-web、spring-security-config保持一致 --> <version>${spring-security.version}</version> </dependency>
- Gradle项目添加依赖:
implementation 'org.springframework.security:spring-security-oauth2-resource-server:${springSecurityVersion}'
校验版本一致性:确保
spring-security-core、spring-security-web、spring-security-config和spring-security-oauth2-resource-server的版本完全相同,避免版本冲突。清理重建项目:添加依赖后执行
mvn clean install(Maven)或gradle clean build(Gradle),清除旧构建缓存,确保新依赖被正确引入。
内容的提问来源于stack exchange,提问作者Gerald Mathabela
相关产品推荐
相关产品推荐

