spring-security 403在Sping Boot 安全性中OpenApiSwagger禁止使用

nnsrf1az  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(172)

我有一个带Spring Security的Sping Boot 应用程序。在配置配置类localhost后,Swagger返回403禁止。我不知道是什么问题。

  • 403禁止访问
    安全配置:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
            throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.authorizeRequests()
            .antMatchers("/api/user/login").permitAll()
            .anyRequest().authenticated();

        return http.build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
                           .antMatchers("/api/user/auth")
                           .antMatchers("/v3/api-docs")
                           .antMatchers("/swagger-resources/**")
                           .antMatchers("/swagger-ui.html")
                           .antMatchers("/configuration/**")
                           .antMatchers("/webjars/**")
                           .antMatchers("/public");
    }
}

build.gradle:

dependencies {
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.7.2'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '2.7.2'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.7.2'

    implementation group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '9.4.1.jre16'

    implementation group: 'org.json', name: 'json', version: '20220320'

    implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.9'

    implementation group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.1'

    compileOnly 'org.projectlombok:lombok:1.18.24'

    annotationProcessor 'org.projectlombok:lombok:1.18.24'
}

P.S.请不要建议从WebSecurityConfigurerAdapter继承该类,因为在我的Spring Security版本中不赞成使用该类。

6fe3ivhb

6fe3ivhb1#

您可以在Web安全配置中使用“/swagger-ui/**”,而不是“/swagger-ui. html”。

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring()
                       .antMatchers("/api/auth/**")
                       .antMatchers("/v3/api-docs/**")
                       .antMatchers("configuration/**")
                       .antMatchers("/swagger*/**")
                       .antMatchers("/webjars/**")
                       .antMatchers("/swagger-ui/**");
}

您是否将springdoc.swagger-ui.path放入应用程序属性文件中?

相关问题