spring boot 加入拦截器后swagger不能访问(亲测有效)

前言

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

不能访问的原因

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

解决方案

配置静态资源访问拦截,定义静态资源的映射,将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地址了。
在这里插入图片描述

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值