Spring Boot 请求头token拦截 Swagger 支持请求头

适用接口需授权token才能调用的场景

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

    //添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //接口签名认证拦截器
        registry.addInterceptor(new HandlerInterceptorAdapter() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                Result result = new Result();
                String token = request.getHeader("token");
                //token 校验
                if (null == token) {
                    result.setCode(ResultCode.UNAUTHORIZED).setMessage("请求 header 缺少 token");
                    responseResult(response, result);
                    return false;
                }
                //TODO 进一步校验
                //endregion

                return true;
            }
        }).excludePathPatterns("/oauth/**");
    }

}        

其中,excludePathPatterns 为不必校验的路由,如 申请token接口

如果你用了 Swagger ui,会导致swagger页面也被拦截,再排除

.excludePathPatterns("/oauth/**")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");

这样,swagger就能正常访问了。但默认是不支持请求头的,开发还是不方便,改配置如下

 1 @Configuration
 2 @EnableSwagger2
 3 public class Swagger2Configurer {
 4 
 5     @Bean
 6     public Docket createRestApi(){
 7         ParameterBuilder ticketPar = new ParameterBuilder();
 8         List<Parameter> pars = new ArrayList<>();
 9         ticketPar.name("token").description("user ticket")
10                 .modelRef(new ModelRef("string")).parameterType("header")
11                 .required(false).build(); //header中的token参数非必填,传空也可以
12         pars.add(ticketPar.build());    //根据每个方法名也知道当前方法在设置什么参数
13 
14         return new Docket(DocumentationType.SWAGGER_2)
15                 .apiInfo(apiInfo())
16                 .select()
17                 .apis(RequestHandlerSelectors.basePackage("com.***.pub"))
18                 .paths(PathSelectors.any())
19                 .build()
20                 .globalOperationParameters(pars);
21     }
22 
23     private ApiInfo apiInfo() {
24         return new ApiInfoBuilder()
25                 .title("*********开放接口")
26                 .version("1.0.0")
27                 .build();
28     }
29 }

 如下图

 

posted @ 2020-07-03 13:34  邱@cnblogs  阅读(1849)  评论(0编辑  收藏  举报