要解决Swagger阻止安全过滤器链中的API注解的问题,并允许通过Postman进行访问,可以采取以下步骤:
确保在Spring Boot项目中已经正确配置了Swagger。
创建一个自定义注解,用于标记需要在Swagger中显示的API。例如,可以创建一个@SwaggerAnnotation
注解。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SwaggerAnnotation {
}
@SwaggerAnnotation
注解。@RestController
public class MyController {
@SwaggerAnnotation
@GetMapping("/api/mypath")
public String myMethod() {
// API逻辑
}
}
@SwaggerAnnotation
注解的API方法添加到Swagger的文档中。import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(SwaggerAnnotation.class))
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
// Swagger文档信息
}
}
WebSecurityConfigurerAdapter
的子类来实现。import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private Environment environment;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs", "/webjars/**")
.permitAll()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.csrf()
.disable();
// 如果还有其他安全配置,请在此处添加
}
}
确保在Pom.xml文件中添加了Swagger和Spring Security的相关依赖。
启动应用程序,并使用Postman进行访问。现在,Swagger应该不会阻止进入安全过滤器链中带有@SwaggerAnnotation
注解的API,并且只有需要身份验证的API才会受到Spring Security的限制。