前言

想让项目中所有请求都必须携带权限认证信息才能请求,所以给项目配置了拦截器,配置完拦截器之后发现swagger地址访问不了了,没有加之前是可以正常访问的。

不能访问的原因

小编分析了一下原因,拦截器要求所有请求(如get,post)都携带权限认证信息请求,但是swagger地址打开的时候默认是以get方式请求的,这个时候并不没有权限认证信息携带着,所以被拦截器给拦截了。既然这样那我是不是就可以把swagger地址过滤掉,意思是不拦截swagger地址,或者把它当成是一个静态资源去访问。

spring boot 加入拦截器后swagger不能访问(亲测有效)_静态资源spring boot 加入拦截器后swagger不能访问(亲测有效)_静态资源_02

解决方案

配置静态资源访问拦截,定义静态资源的映射,将swagger地址当成普通的html静态资源去访问就可以了。

package com.tensquare.user.config;

import com.tensquare.user.interceptor.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

@Autowired
private JwtInterceptor jwtInterceptor;

/***
* addPathPatterns("/**"):拦截所有请求
* excludePathPatterns: 不拦截的请求
* @param registry
*/
protected void addInterceptors(InterceptorRegistry registry){
//注册拦截器要声明拦截器对象和要拦截的请求
registry.addInterceptor(jwtInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/**/login/**")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
}

/***
* 配置静态资源访问拦截
* @param registry
*/
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}

配置后再次运行就能访问swagger地址了。

spring boot 加入拦截器后swagger不能访问(亲测有效)_静态资源_03