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

Spring Security 6集成OpenApi报HTTP 403错误的排查与解决

Spring Security 6 + Spring Boot 3 下Swagger UI访问返回403错误

问题场景

刚接触Spring Security,配置完Security规则后,用Postman可以正常调用接口,但访问Swagger UI(OpenApi)时始终返回HTTP 403错误。未添加Security配置前,Swagger UI可以正常使用。

使用版本

  • Spring Boot 3.0.6
  • Spring Security 6

现有代码

Security配置类

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder encoder){
        UserDetails admin = User.withUsername("msg")
                .password(encoder.encode("123"))
                .roles("ADMIN", "USER")
                .build();
        UserDetails user = User.withUsername("user")
                .password(encoder.encode("123"))
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(admin, user);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        return http.httpBasic()
                .and()
                .authorizeHttpRequests()
                .requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
                //.requestMatchers("/users").authenticated()
                .requestMatchers(HttpMethod.POST,"/users/**").hasRole("USER")
                .requestMatchers("/users/**").hasRole("ADMIN")
                .and()
                .csrf().disable()
                .formLogin().disable()
                .build();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

原pom.xml依赖

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

尝试过的操作

添加了springdoc-openapi-security依赖,但问题依旧,访问http://localhost:9090/swagger-ui.html仍返回403。

解决办法

更换为Spring Boot 3.0适配的OpenApi版本依赖,问题解决:

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

该版本是Spring Boot 3.0官方支持的OpenApi依赖版本,替换后Swagger UI可正常访问,接口调用也不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:25:23