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

SpringBoot JWT认证Controller测试遇JwtGrantedAuthoritiesConverter类未找到错误

解决方案

问题1:Jwt类找不到的处理

出现org.springframework.security.oauth2.jwt.Jwt类找不到的错误,是因为测试依赖缺少Spring Security OAuth2 JWT相关包。SecurityMockMvcRequestPostProcessors.jwt()属于Spring Security Test对OAuth2 JWT的测试支持,需引入对应依赖:

如果是Maven项目,在pom.xml中添加:

<!-- Spring Security OAuth2 Resource Server 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    <scope>test</scope>
</dependency>
<!-- 确保Spring Security Test依赖存在 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

如果是Gradle项目,添加:

testImplementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
testImplementation 'org.springframework.security:spring-security-test'

同步依赖后即可找到Jwt类。

问题2:Attribute name must not be null异常的处理

这个异常通常是自定义JWTAuthorizationFilter或WebSecurityConfig处理认证信息时未处理空值,或原生@WithMockUser/with(user("user"))生成的认证对象与自定义过滤器逻辑不兼容导致的。

方案A:修复自定义过滤器的空值处理

检查JWTAuthorizationFilter代码,在解析用户信息、获取认证属性的位置增加非空判断,示例:

// 获取用户主体时判断非空
String username = (String) authentication.getPrincipal();
if (username == null) {
    throw new BadCredentialsException("无效令牌");
}
// 获取自定义属性时判断非空
Object attribute = authentication.getAttributes().get("attributeName");
if (attribute == null) {
    // 处理逻辑:设默认值或抛出合理异常
}

方案B:手动构造认证对象(推荐)

因为使用自定义JWT认证逻辑,原生@WithMockUser可能无法适配,可在测试方法中手动构造Authentication对象并存入SecurityContext,示例:

@Test
void testApi() throws Exception {
    // 构造认证对象,可根据自定义逻辑调整
    Authentication auth = new UsernamePasswordAuthenticationToken(
            "testUser", 
            null, 
            AuthorityUtils.createAuthorityList("ROLE_USER")
    );
    // 存入SecurityContext
    SecurityContextHolder.getContext().setAuthentication(auth);

    // 执行MockMvc请求
    mockMvc.perform(get("/api/your-endpoint")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
}

方案C:配置测试环境专用Security

创建测试环境的Security配置,禁用自定义JWT过滤器,允许@WithMockUser生效:

@Profile("test")
@Configuration
public class TestWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().disable();
    }
}

在测试类上添加@ActiveProfiles("test"),测试时会使用该配置,@WithMockUser即可正常工作。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:04:56