如何配置 Spring Security 以允许在没有身份验证的情况下访问 Swagger URL

我的项目有 Spring Security。 主要问题: 无法访问在 http://localhost:8080/api/v2/api-docs的虚张声势的 URL。它说丢失或无效的授权头。

浏览器窗口的屏幕快照 我的 pom.xml 有以下条目

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>


<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>

SwaggerConfig:

@Configuration
@EnableSwagger2
public class SwaggerConfig {


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


private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", "myeaddress@company.com", "License of API", "API license URL");
return apiInfo;
}

AppConfig:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.musigma.esp2" })
@Import(SwaggerConfig.class)
public class AppConfig extends WebMvcConfigurerAdapter {


// ========= Overrides ===========


@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
}


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");


registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}

Xml 条目:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.musigma.esp2.configuration.AppConfig
com.musigma.esp2.configuration.WebSecurityConfiguration
com.musigma.esp2.configuration.PersistenceConfig
com.musigma.esp2.configuration.ACLConfig
com.musigma.esp2.configuration.SwaggerConfig
</param-value>
</context-param>

WebSecurityConfig:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackages = { "com.musigma.esp2.service", "com.musigma.esp2.security" })
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(this.unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/auth/login", "/auth/logout").permitAll()
.antMatchers("/api/**").authenticated()
.anyRequest().authenticated();


// custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication
httpSecurity.addFilterBefore(loginFilter(), UsernamePasswordAuthenticationFilter.class);


// custom Token based authentication based on the header previously given to the client
httpSecurity.addFilterBefore(new StatelessTokenAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class);
}
}
226593 次浏览

将它添加到 WebSecurityConfiguration 类中应该可以完成这个任务。

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {


@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}


}

I updated with /configuration/** and /swagger-resources/** and it worked for me.

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**");


}

我在使用 SpringBoot2.0.0时遇到了同样的问题。M7 + Spring Security + Springfox2.8.0.我使用以下安全配置解决了这个问题,该配置允许公众访问 Swagger UI 资源。

更新于2021年1月的答案: 支持 Springfox3

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


private static final String[] AUTH_WHITELIST = {
// -- Swagger UI v2
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
// -- Swagger UI v3 (OpenAPI)
"/v3/api-docs/**",
"/swagger-ui/**"
// other public endpoints of your API may be appended to this array
};




@Override
protected void configure(HttpSecurity http) throws Exception {
http.
// ... here goes your custom security configuration
authorizeRequests().
antMatchers(AUTH_WHITELIST).permitAll().  // whitelist Swagger UI resources
// ... here goes your custom security configuration
antMatchers("/**").authenticated();  // require authentication for any endpoint that's not whitelisted
}


}

Considering all of your API requests located with a url pattern of /api/.. you can tell spring to secure only this url pattern by using below configuration. Which means that you are telling spring what to secure instead of what to ignore.

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

如果你的 springfox 版本高于2.5,应该添加如下 WebSecurityConfiguration:

@Override
public void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.authorizeRequests()
.antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html", "/webjars/**").permitAll()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.csrf().disable();
}

这一页或多或少都有答案,但不是所有的答案都在同一个地方。我也在处理同样的问题,并且花了相当多的时间在上面。现在我有一个更好的理解,我想在这里分享它:

用 Spring 网络安全启用 Swagger ui:

如果默认情况下您启用了 SpringWebsecurity,它将阻止所有对应用程序的请求,并返回401。但是,对于在浏览器 swagger-ui.html 中加载的 swagger ui,需要进行几个调用来收集数据。最好的调试方法是在浏览器中打开 swagger-ui.html (比如 google chrome)并使用开发者选项(‘ F12’键)。您可以看到在加载页面时发出的几个调用,如果 swagger-ui 没有完全加载,那么其中一些可能会失败。

你可能需要告诉 Springwebsecurity 忽略一些虚张声势路径模式的身份验证。 I am using swagger-ui 2.9.2 and in my case below are the patterns that i had to ignore:

但是,如果您使用的是不同的版本,您的版本可能会发生变化。正如我之前所说的,你可能需要在你的浏览器中用开发者选项来解决你的问题。

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui",
"/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
, "/webjars/**", "/csrf", "/");
}
}

用拦截器启用 swagger ui

通常,您可能不希望拦截 swagger-ui.html 发出的请求。排除以下几种自吹自擂的方式是这样的:

大多数情况下,Web 安全和拦截器的模式将是相同的。

@Configuration
@EnableWebMvc
public class RetrieveCiamInterceptorConfiguration implements WebMvcConfigurer {


@Autowired
RetrieveInterceptor validationInterceptor;


@Override
public void addInterceptors(InterceptorRegistry registry) {


registry.addInterceptor(validationInterceptor).addPathPatterns("/**")
.excludePathPatterns("/v2/api-docs", "/configuration/ui",
"/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
, "/webjars/**", "/csrf", "/");
}


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");


registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}


}

Since you may have to enable @EnableWebMvc to add interceptors you may also have to add resource handlers to swagger similar to i have done in the above code snippet.

仅限于与斯威格相关的资源:

.antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/webjars/springfox-swagger-ui/**");

这是 春天保安公司的大摇大摆的完整解决方案。我们可能只想在开发和 QA 环境中启用 Swagger,并在生产环境中禁用它。因此,我使用一个属性(prop.swagger.enabled)作为标志,以绕过只在开发/qa 环境中使用 swagger-ui 的 Spring 安全性身份验证。

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {


@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;


@Bean
public Docket SwaggerConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(enableSwagger)
.select()
.apis(RequestHandlerSelectors.basePackage("com.your.controller"))
.paths(PathSelectors.any())
.build();
}


@Override
public void configure(WebSecurity web) throws Exception {
if (enableSwagger)
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (enableSwagger) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
}

对于那些使用新的狂妄自大3版本 org.springdoc:springdoc-openapi-ui的人

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {


@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**");
}
}

我正在使用 SpringBoot5。我有这个控制器,我希望一个未经身份验证的用户调用。

  //Builds a form to send to devices
@RequestMapping(value = "/{id}/ViewFormit", method = RequestMethod.GET)
@ResponseBody
String doFormIT(@PathVariable String id) {
try
{
//Get a list of forms applicable to the current user
FormService parent = new FormService();

下面是我在配置中所做的。

  @Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(
"/registration**",
"/{^[\\\\d]$}/ViewFormit",

Hope this helps....

一些安全配置,你准备好大摇大摆地向所有人开放

为了斯威格 V2

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {




private static final String[] AUTH_WHITELIST = {
// -- swagger ui
"/v2/api-docs",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**"
};


@Override
protected void configure(HttpSecurity http) throws Exception {


// ... here goes your custom security configuration
http.authorizeRequests().
antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
antMatchers("/**").authenticated(); // others need auth
}


}

为了斯威格 V3

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {




private static final String[] AUTH_WHITELIST = {
// -- swagger ui
"/v2/api-docs",
"/v3/api-docs",
"/swagger-resources/**",
"/swagger-ui/**",
};


@Override
protected void configure(HttpSecurity http) throws Exception {


// ... here goes your custom security configuration
http.authorizeRequests().
antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
antMatchers("/**").authenticated(); // others need auth
}


}

仅仅为了使斯威格能够使用 Spring boot 2.5.4Springfox Swagger2:3.0.0,以下的改变对我来说就足够了:- .authorizeRequests().antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui/**").permitAll().and()

感谢大家在这个帖子里的建议!

Add a Bean like this:

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.authorizeExchange()
.pathMatchers(
"/v2/api-docs",
"/swagger-ui/**",
"/swagger-resources/**",
"/*/swagger-resources/**",
"/*/v2/api-docs")
.permitAll()
.and()
.authorizeExchange()
.anyExchange()
.permitAll();
http.httpBasic().disable();
http.csrf().disable();
return http.build();
}

对于没有 WebSecurityConfigurerAdapter 的 Spring Security,它看起来像(springdoc-openapi) :

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

请参见 < a href = “ https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigerAdapter# Configuring-WebSecurity”rel = “ nofollow noReferrer”> ConfigingWebSecurity