java 错误403 OpenApi与SpringBoot安全过滤器链

wvt8vs2t  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(132)

我试图将OpenApi文档添加到我的spring-boot应用程序中,但当我尝试连接到/v3/api-docs和/swagger-ui时,出现错误403。
我正在使用springBoot 3.0.1和springdoc-openapi-ui依赖项

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.15</version>
</dependency>

我尝试在安全过滤器链中添加permitAll请求匹配。

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        AuthenticationFilter authenticationFilter = new AuthenticationFilter(customAuthenticationManager, userService);
        authenticationFilter.setFilterProcessesUrl("/authenticate");
        http.cors().and().csrf().disable()
                .authorizeHttpRequests()
                .requestMatchers("/swagger-ui.html",
                        "/swagger-ui/**",
                        "/swagger-resources/**",
                        "/swagger-resources",
                        "/v3/api-docs/**",
                        "/proxy/**",
                        "/swagger-ui.html").permitAll()
                .requestMatchers(HttpMethod.POST, "/user/register").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(authenticationFilter)
                .addFilterAfter(new JWTAuthorizationFilter(), AuthenticationFilter.class);
        return http.build();
    }

以及使用web.ignore()添加WebSecurityCustomizerbean

@Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers("/v3/api-docs/**","/proxy/**", "/swagger-ui/**", "/swagger-resources/**", "/v3/api-docs/**");
    }
p8h8hvxi

p8h8hvxi1#

依赖关系

首先,您需要为Sping Boot 3使用不同的依赖项:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.0.4</version>
</dependency>

查找最新版本here

安全配置

对我来说,你的安全配置看起来很好。我也排除了"/webjars/swagger-ui/**",但我不确定,如果它真的是必要的。下面的配置对我来说是有效的:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
class WebSecurityConfiguration {

    private static final String[] SWAGGER_PATHS = {"/swagger-ui.html", "/v3/api-docs/**", "/swagger-ui/**", "/webjars/swagger-ui/**"};

    @Bean
    SecurityFilterChain filterChain(final HttpSecurity http) throws Exception {
        return http
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(SWAGGER_PATHS).permitAll()
                        .anyRequest().authenticated())
                .build();
    }
}

相关问题