Error No qualifying bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' available

new9mtju  于 2023-05-22  发布在  Spring
关注(0)|答案(2)|浏览(335)

我试图为我的控制器编写测试,但测试环境无法加载给定的stackTrace。

@PreAuthorize("hasAuthority('my.scope')")
    @GetMapping(value = "/path", produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Set<String>>> getPath() {
        return myService.pathFunction()
            .map(ResponseEntity::ok);
    }

下面是我如何配置我的安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebConfig extends WebSecurityConfigurerAdapter {

    private static final String PRINCIPAL = "sub";

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        JwtAuthenticationConverter authenticationConverter =
            new JwtAuthenticationConverter();
        authenticationConverter.setJwtGrantedAuthoritiesConverter(...);
        authenticationConverter.setPrincipalClaimName(PRINCIPAL);

        http.csrf().disable()
            .cors()
            .and()
            .authorizeRequests().antMatchers("/actuator/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .oauth2ResourceServer()
            .jwt()
            .jwtAuthenticationConverter(authenticationConverter);
    }
}

控制器按需工作,但我的测试失败,出现此错误。我没有使用任何客户JwtDecoder

@WebMvcTest(controllers = Controller.class)
class ControllerTest {

    @MockBean
    private MyService myService;

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithMockUser(authorities = {"my.scope"})
    void controllerTest() throws Exception{
        Map<String, Set<String>> mapResponse = Map.of("key", Set.of("foo1", "foo2"));
        Mockito.when(myService.pathFunction()).thenReturn(Optional.of(mapResponse));

        MockHttpServletResponse result = mockMvc.perform(get("/configuration/api-registry")
                .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn()
            .getResponse();

        String response = result.getContentAsString();
        assertTrue(response.contains("foo1"));
    }

}

如何运行此测试?

java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.BeanCreationException: 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 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' available
    ...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' available
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
    ... 90 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' available
    at ...
vfh0ocws

vfh0ocws1#

我在测试中添加了模拟解码器作为

@MockBean
private JwtDecoder jwtDecoder;

测试开始了!

vptzau2j

vptzau2j2#

我在使用@SpringBootTest时遇到了这个错误。从spring Boot 版本2.5.12升级到2.7.8时开始出现。
我可以通过改变

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

相关问题