shu*_*har 65 spring-mvc swagger swagger-ui swagger-2.0 springfox
我的项目有Spring Security.主要问题:无法访问http:// localhost:8080/api/v2/api-docs中的 swagger URL .它表示缺少或无效的授权标头.
浏览器窗口的屏幕截图 My 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>
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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/");
}
Run Code Online (Sandbox Code Playgroud)
web.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>
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 120
将此添加到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/**");
}
}
Run Code Online (Sandbox Code Playgroud)
小智 19
我使用/ configuration/**和/ swagger-resources/**进行了更新,它对我有用.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**");
}
Run Code Online (Sandbox Code Playgroud)
Den*_*lot 17
对于那些使用较新的 swagger 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/**");
}
}
Run Code Online (Sandbox Code Playgroud)
naX*_*aXa 15
我使用Spring Boot 2.0.0.M7 + Spring Security + Springfox 2.8.0时遇到了同样的问题.我使用以下安全配置解决了这个问题,该配置允许公共访问Swagger UI资源.
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
// -- swagger ui
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**"
// 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
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
如果您的 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();
}
Run Code Online (Sandbox Code Playgroud)
一些安全配置,你就可以向所有人开放了
对于斯瓦格 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
}
}
Run Code Online (Sandbox Code Playgroud)
适用于斯瓦格 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
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 Spring Boot 3,则需要使用:正如文档简介springdoc-openapi-starter-webmvc-ui中所写。
并使用安全配置,如下所示:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true, prePostEnabled = true, jsr250Enabled = true)
@RequiredArgsConstructor
public class SecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf().disable()
.authorizeHttpRequests(a -> a
.requestMatchers("/v3/**", "/swagger-ui/**").permitAll()
.anyRequest().authenticated()
).build();
}
}
Run Code Online (Sandbox Code Playgroud)
http://{your host}:{your port}/swagger-ui/index.htmlhttp://{your host}:{your port}/v3/api-docshttp://{your host}:{your port}/v3/api-docs.yaml此页面或多或少有答案,但所有答案都不在一处。我正在处理同样的问题并花了相当多的时间。现在我有了更好的理解,我想在这里分享:
我使用 Spring websecurity 启用 Swagger ui:
如果您默认启用了 Spring Websecurity,它将阻止对应用程序的所有请求并返回 401。但是,为了在浏览器中加载 swagger-ui.html,需要多次调用来收集数据。最好的调试方法是在浏览器(如谷歌浏览器)中打开 swagger-ui.html 并使用开发人员选项(“F12”键)。您可以看到页面加载时进行的多个调用,如果 swagger-ui 未完全加载,则可能其中一些调用失败。
您可能需要告诉 Spring websecurity 忽略几种 swagger 路径模式的身份验证。我正在使用 swagger-ui 2.9.2,在我的例子中,下面是我必须忽略的模式:
但是,如果您使用不同的版本,您的版本可能会发生变化。正如我之前所说,您可能必须通过浏览器中的开发人员选项来找出您的。
@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", "/");
}
}
Run Code Online (Sandbox Code Playgroud)
II 使用拦截器启用 swagger ui
通常,您可能不想拦截 swagger-ui.html 发出的请求。要排除以下几种 swagger 模式,代码如下:
大多数网络安全和拦截器的案例模式都是相同的。
@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/");
}
}
Run Code Online (Sandbox Code Playgroud)
由于您可能必须启用 @EnableWebMvc 来添加拦截器,因此您可能还必须向 swagger 添加资源处理程序,类似于我在上面的代码片段中所做的操作。
| 归档时间: |
|
| 查看次数: |
75169 次 |
| 最近记录: |