springboot security 整合swagger无法访问

---
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();
    }
}

```

## 问题解决!
               
为了在Swagger中添加token,可以使用Spring Security来保护API并生成token。以下是如何在Spring Boot应用程序中使用SwaggerSpring Security整合token的步骤: 1. 添加Spring Security和JWT依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency> ``` 2. 创建Spring Security配置类 创建一个类,继承WebSecurityConfigurerAdapter并重写configure(HttpSecurity http)方法。在该方法中,配置Spring Security以保护API并生成token。以下是一个示例: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; @Bean public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() .authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() .and() .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } } ``` 3. 创建JWT工具类 创建一个类,用于生成和解析JWT token。以下是一个示例: ``` @Component public class JwtUtils { @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private int expiration; public String generateToken(Authentication authentication) { UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal(); Date now = new Date(); Date expiryDate = new Date(now.getTime() + expiration); return Jwts.builder() .setSubject(userPrincipal.getUsername()) .setIssuedAt(now) .setExpiration(expiryDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public String getUsernameFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject(); } public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(secret).parseClaimsJws(authToken); return true; } catch (SignatureException ex) { log.error("Invalid JWT signature"); } catch (MalformedJwtException ex) { log.error("Invalid JWT token"); } catch (ExpiredJwtException ex) { log.error("Expired JWT token"); } catch (UnsupportedJwtException ex) { log.error("Unsupported JWT token"); } catch (IllegalArgumentException ex) { log.error("JWT claims string is empty"); } return false; } } ``` 4. 创建JWT认证过滤器 创建一个类,用于验证token并将用户信息添加到Spring Security上下文中。以下是一个示例: ``` public class JwtAuthenticationFilter extends OncePerRequestFilter { @Autowired private JwtUtils jwtUtils; @Autowired private UserDetailsService userDetailsService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = getJwtFromRequest(request); if (StringUtils.hasText(jwt) && jwtUtils.validateToken(jwt)) { String username = jwtUtils.getUsernameFromToken(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception ex) { log.error("Could not set user authentication in security context", ex); } filterChain.doFilter(request, response); } private String getJwtFromRequest(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } return null; } } ``` 5. 在Swagger中添加token 在Spring Boot应用程序中添加Swagger,并在Swagger配置类中添加以下代码: ``` @Configuration @EnableSwagger2 public class SwaggerConfig { @Autowired private JwtUtils jwtUtils; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .securityContexts(Arrays.asList(securityContext())) .securitySchemes(Arrays.asList(apiKey())) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } private ApiKey apiKey() { return new ApiKey("JWT", "Authorization", "header"); } private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(Arrays.asList(new SecurityReference("JWT", new AuthorizationScope[]{}))) .forPaths(PathSelectors.any()) .build(); } @Bean public SecurityConfiguration security() { return SecurityConfigurationBuilder.builder() .clientId(null) .clientSecret(null) .realm(null) .appName(null) .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean public UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() .displayRequestDuration(true) .validatorUrl("") .build(); } @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/"); } @Bean public SecurityConfiguration securityConfiguration() { return SecurityConfigurationBuilder.builder() .clientId("test-app-client-id") .clientSecret("test-app-client-secret") .realm("test-app-realm") .appName("test-app") .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean public SecurityConfiguration securityConfiguration() { return SecurityConfigurationBuilder.builder() .clientId("test-app-client-id") .clientSecret("test-app-client-secret") .realm("test-app-realm") .appName("test-app") .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean public OAuth securitySchema() { List<AuthorizationScope> authorizationScopeList = new ArrayList<>(); authorizationScopeList.add(new AuthorizationScope("read", "read all")); authorizationScopeList.add(new AuthorizationScope("write", "access all")); List<GrantType> grantTypes = new ArrayList<>(); GrantType passwordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant("http://localhost:8080/auth/token"); grantTypes.add(passwordCredentialsGrant); return new OAuth("oauth2schema", authorizationScopeList, grantTypes); } @Bean public SecurityConfiguration securityInfo() { return new SecurityConfiguration( "test-app-client-id", "test-app-client-secret", "test-app-realm", "test-app", "", ApiKeyVehicle.HEADER, "Authorization", "," ); } @Bean public SecurityConfiguration security() { return SecurityConfigurationBuilder.builder() .clientId("test-app-client-id") .clientSecret("test-app-client-secret") .realm("test-app-realm") .appName("test-app") .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean public UiConfiguration uiConfiguration() { return new UiConfiguration( null, "none", "alpha", "schema", UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L ); } } ``` 完成以上步骤后,您就可以在Swagger中使用token来访问受保护的API了。在Swagger界面的右上方,单击“Authorize”按钮并输入您的token即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值