Swagger 在 Spring Security 6 之后不工作

问题描述 投票:0回答:0

我一直在我所有的 Spring Boot 应用程序中使用 Swagger,在开始使用最新版本的 Spring Security 之后,我意识到之前的配置似乎不起作用并抛出“”需要完整身份验证才能访问此资源 “尝试打开 swagger 页面时出错。

这里是相关步骤

1. 添加maven依赖:

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-boot-starter</artifactId>
   <version>3.0.0</version>
</dependency>

2.新建一个类,SwaggerConfig:

@Configuration
public class SwaggerConfig {

    private ApiInfo apiInfo() {
        return new ApiInfo(/* parameters */);
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

}

3. 添加必要的 url 到 SecurityConfig(注意我使用

requestMatchers
因为
antMatchers
已经过时了。

另请注意,我尝试删除

"/api/v1/auth/**"
然后看到它是不允许的。这意味着,这种方法是允许
AUTH_WHITELIST
.

中的 url

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final UserDetailsServiceImpl userDetailsService;

    private final AuthEntryPointJwt authEntryPointJwt;

    private static final String[] AUTH_WHITELIST = {
            "/api/v1/auth/**",

            // --- for Swagger UI v2
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**",

            // --- for Swagger UI v3
            "/v3/api-docs/**",
            "/swagger-ui/**"
    };

    // code omitted

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .cors().and()
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(AUTH_WHITELIST).permitAll()
                .anyRequest().authenticated()
            )
                .exceptionHandling().authenticationEntryPoint(
                     authEntryPointJwt).and()
                     .sessionManagement(sess -> sess.sessionCreationPolicy(
                     SessionCreationPolicy.STATELESS));

        httpSecurity.authenticationProvider(authenticationProvider());
        httpSecurity.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        return httpSecurity.build();
    }
}

4. 在application.yml中添加以下变量:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
    throw-exception-if-no-handler-found: true

那么,这个实现有什么问题?

java spring spring-boot spring-security swagger
© www.soinside.com 2019 - 2024. All rights reserved.