--- title: springboot2.x整合swagger + security 的问题 date: 2020-04-06 15:56:59 tags: ['spring','aop'] --- ## 问题: 当springboot2.x整合swagger的时候,没有遇到任何困难,但是当引入security的时候,问题十分严重,直接就导致swagger进入不了了, 几经折腾,才终于发现了问题。 期间遇到的问题: 1.swagger需要登录 2.swagger进不去,直接无法访问,进入springboot错误界面/error 3.网上一大堆说法不一样的问题 ## 问题排查 1.首先我想知道当我注册HandlerInterceptor的时候是否注册有效,再preHandle里面写一个sytem打印输出。 2.注册有效,那么是不是.excludePathPatterns()无效呢,这个就十分难进行排查,但是这里可以采用以下代码。 ``` @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("token验证中"); /*StringBuffer url = request.getRequestURL(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8")); } catch (IOException e) { e.printStackTrace(); } String line = null; StringBuilder sb = new StringBuilder(); try { while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } System.out.println("请求地址:{}, 请求参数:{}" + url + sb.toString());*/ } ``` <!--more--> 得到请求路径,这样可以帮助我们判断是否去拦截成功,那么到底是哪儿有问题呢? ## springboot 2.x 依赖spring5 所以在拦截器方面会有某些不一致的情况,下面贴出spring部分源码: #### spring 4.x 处理Interceptor ``` /** * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped * resource handlers. To configure resource handling, override * {@link #addResourceHandlers}. */ @Bean public HandlerMapping resourceHandlerMapping() { ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext, this.servletContext, mvcContentNegotiationManager()); addResourceHandlers(registry); AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); if (handlerMapping != null) { handlerMapping.setPathMatcher(mvcPathMatcher()); handlerMapping.setUrlPathHelper(mvcUrlPathHelper()); // 此处固定添加了一个Interceptor handlerMapping.setInterceptors(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider())); handlerMapping.setCorsConfigurations(getCorsConfigurations()); } else { handlerMapping = new EmptyHandlerMapping(); } return handlerMapping; } ``` ### spring 5.x处理Interceptor ``` /** * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped * resource handlers. To configure resource handling, override * {@link #addResourceHandlers}. */ @Bean public HandlerMapping resourceHandlerMapping() { Assert.state(this.applicationContext != null, "No ApplicationContext set"); Assert.state(this.servletContext != null, "No ServletContext set"); ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext, this.servletContext, mvcContentNegotiationManager(), mvcUrlPathHelper()); addResourceHandlers(registry); AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); if (handlerMapping != null) { handlerMapping.setPathMatcher(mvcPathMatcher()); handlerMapping.setUrlPathHelper(mvcUrlPathHelper()); // 此处是将所有的HandlerInterceptor都添加了(包含自定义的HandlerInterceptor) handlerMapping.setInterceptors(getInterceptors()); handlerMapping.setCorsConfigurations(getCorsConfigurations()); } else { handlerMapping = new EmptyHandlerMapping(); } return handlerMapping; } /** * Provide access to the shared handler interceptors used to configure * {@link HandlerMapping} instances with. This method cannot be overridden, * use {@link #addInterceptors(InterceptorRegistry)} instead. */ protected final Object[] getInterceptors() { if (this.interceptors == null) { InterceptorRegistry registry = new InterceptorRegistry(); // 此处传入新new的registry对象,在配置类当中设置自定义的HandlerInterceptor后即可获取到 addInterceptors(registry); registry.addInterceptor(new ConversionServiceExposingInterceptor(mvcConversionService())); registry.addInterceptor(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider())); this.interceptors = registry.getInterceptors(); } return this.interceptors.toArray(); } ``` ## 从spring5源码可以看出,这里可以直接这样配置,这里根据自己的需求进行更改: ``` package com.hyfj.soft.springbootdemo.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.cors.CorsUtils; /** * 安全配置类 * @author cayden */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { /** * 配置安全 * */ @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() .loginPage("/needLogin") .loginProcessingUrl("/login").permitAll() .and() .authorizeRequests() // 授权不需要登录权限的URL .antMatchers("/needLogin", "/swagger*//**", "/v2/api-docs", "/webjars*//**").permitAll() .requestMatchers(CorsUtils::isPreFlightRequest).permitAll(). and().exceptionHandling(). and().cors().and().csrf().disable(); } } ``` ## 问题解决!
springboot security 整合swagger无法访问
最新推荐文章于 2024-07-14 07:04:52 发布