当前位置:   article > 正文

Spring Cloud Gateway网关集成Swagger2.9.2 设置全局token_spring cloud gateway整合swagger 2.9.2

spring cloud gateway整合swagger 2.9.2

正常使用时,我们的接口需要登陆才能访问的。即登录时,要传一个登陆后的token才能访问的。
那这个怎么设置,才可以让所有接口都允许登陆后访问呢。
设置全局token解决办法如下:

1. 在pom中加入依赖

  1. <properties>
  2. <swagger.version>2.9.2</swagger.version>
  3. </properties>
  4. <!-- swagger -->
  5. <dependency>
  6. <groupId>io.springfox</groupId>
  7. <artifactId>springfox-swagger-ui</artifactId>
  8. <version>${swagger.version}</version>
  9. </dependency>
  10. <dependency>
  11. <groupId>io.springfox</groupId>
  12. <artifactId>springfox-swagger2</artifactId>
  13. <version>${swagger.version}</version>
  14. <exclusions>
  15. <exclusion>
  16. <groupId>io.swagger</groupId>
  17. <artifactId>swagger-models</artifactId>
  18. </exclusion>
  19. </exclusions>
  20. </dependency>
  21. <!-- 2.9.2中默认使用的是 swagger-models-1.5.20 版本,该版本中的example只判断了值是否为空,但是并没有判断值是否是空串,映射上就会报 NumberFormatException 异常 -->
  22. <dependency>
  23. <groupId>io.swagger</groupId>
  24. <artifactId>swagger-models</artifactId>
  25. <version>1.5.21</version>
  26. </dependency>

2. swagger配置如下

  1. @Configuration
  2. @EnableSwagger2
  3. public class SwaggerConfig {
  4. @Bean
  5. public Docket platformApi() {
  6. return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).forCodeGeneration(true)
  7. .select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
  8. .apis(RequestHandlerSelectors.any())
  9. .paths(regex("^.*(?<!error)$"))
  10. .build()
  11. .securitySchemes(securitySchemes())
  12. .securityContexts(securityContexts());
  13. }
  14. private List<ApiKey> securitySchemes() {
  15. List<ApiKey> apiKeyList = new ArrayList();
  16. apiKeyList.add(new ApiKey("token", "token", "header"));
  17. return apiKeyList;
  18. }
  19. private List<SecurityContext> securityContexts() {
  20. List<SecurityContext> securityContexts=new ArrayList<>();
  21. securityContexts.add(
  22. SecurityContext.builder()
  23. .securityReferences(defaultAuth())
  24. .forPaths(PathSelectors.regex("^(?!auth).*$"))
  25. .build());
  26. return securityContexts;
  27. }
  28. List<SecurityReference> defaultAuth() {
  29. AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
  30. AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
  31. authorizationScopes[0] = authorizationScope;
  32. List<SecurityReference> securityReferences = new ArrayList<>();
  33. securityReferences.add(new SecurityReference("token", authorizationScopes));//验证增加(有许多教程说明中这个地方是Authorization,导致不能带入全局token,因为securitySchemes()方法中header写入token,所以这个地方我改为token就可以了)
  34. return securityReferences;
  35. }
  36. private ApiInfo apiInfo() {
  37. return new ApiInfoBuilder().title("接口文档")
  38. .description("用于说明接口使用")
  39. .contact(new Contact("csruan", "", ""))
  40. .license("Apache License Version 2.0")
  41. .version("1.0").build();
  42. }
  43. }

3. 网关中增加配置

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.http.HttpStatus;
  3. import org.springframework.http.ResponseEntity;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import reactor.core.publisher.Mono;
  8. import springfox.documentation.swagger.web.*;
  9. import java.util.Optional;
  10. @RestController
  11. @RequestMapping("/swagger-resources")
  12. public class SwaggerHandler {
  13. @Autowired(required = false)
  14. private SecurityConfiguration securityConfiguration;
  15. @Autowired(required = false)
  16. private UiConfiguration uiConfiguration;
  17. private final SwaggerResourcesProvider swaggerResources;
  18. @Autowired
  19. public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
  20. this.swaggerResources = swaggerResources;
  21. }
  22. @GetMapping("/configuration/security")
  23. public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
  24. return Mono.just(new ResponseEntity<>(
  25. Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
  26. }
  27. @GetMapping("/configuration/ui")
  28. public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
  29. return Mono.just(new ResponseEntity<>(
  30. Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
  31. }
  32. @GetMapping("")
  33. public Mono<ResponseEntity> swaggerResources() {
  34. return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
  35. }
  36. }
  1. import lombok.AllArgsConstructor;
  2. import org.springframework.cloud.gateway.config.GatewayProperties;
  3. import org.springframework.cloud.gateway.route.RouteLocator;
  4. import org.springframework.cloud.gateway.support.NameUtils;
  5. import org.springframework.context.annotation.Primary;
  6. import org.springframework.stereotype.Component;
  7. import springfox.documentation.swagger.web.SwaggerResource;
  8. import springfox.documentation.swagger.web.SwaggerResourcesProvider;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. /**
  12. * 聚合接口文档注册
  13. */
  14. @Component
  15. @Primary
  16. @AllArgsConstructor
  17. public class SwaggerProvider implements SwaggerResourcesProvider {
  18. public static final String API_URI = "/v2/api-docs";
  19. private final RouteLocator routeLocator;
  20. private final GatewayProperties gatewayProperties;
  21. @Override
  22. public List<SwaggerResource> get() {
  23. List<SwaggerResource> resources = new ArrayList<>();
  24. List<String> routes = new ArrayList<>();
  25. //取出gateway的route
  26. routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
  27. //结合配置的route-路径(Path),和route过滤,只获取有效的route节点
  28. gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
  29. .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
  30. .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
  31. .forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
  32. predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
  33. .replace("/**", API_URI)))));
  34. return resources;
  35. }
  36. private SwaggerResource swaggerResource(String name, String location) {
  37. SwaggerResource swaggerResource = new SwaggerResource();
  38. swaggerResource.setName(name);
  39. swaggerResource.setLocation(location);
  40. swaggerResource.setSwaggerVersion("2.0");
  41. return swaggerResource;
  42. }
  43. }

4. yml

  1. spring:
  2. application:
  3. name: gateway # 服务名称
  4. cloud:
  5. nacos:
  6. discovery:
  7. server-addr: localhost:8848 # 注册中心地址 # 默认是没有密码的
  8. gateway:
  9. discovery:
  10. locator:
  11. enabled: true #表明gateway开启服务注册和发现的功能, 动态路由
  12. lowerCaseServiceId: true
  13. filters:
  14. routes:
  15. - id: test # 唯一id ,随便起,不能重复
  16. uri: lb://test # 匹配注册中心的服务
  17. predicates:
  18. - Path=/test/** # 匹配的规则
  19. filters:
  20. # 去掉路由前缀,访问 localhost:8088/test/v2/api 转发的就是 localhost:8089/v2/api
  21. # 1 : 代表剥离路径的个数
  22. - StripPrefix=1

特别注意:-StripPrefix=1,这个一定不要去掉,不然你就访问不到你服务的swagger,如下图

以上步骤完成,已经在网关中集成了swagger,并可以全局添加token。

下面说明给所有单个接口添加token,swagger配置如下:

  1. import com.google.common.collect.Lists;
  2. import io.swagger.annotations.ApiOperation;
  3. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import springfox.documentation.builders.ApiInfoBuilder;
  7. import springfox.documentation.builders.ParameterBuilder;
  8. import springfox.documentation.builders.PathSelectors;
  9. import springfox.documentation.builders.RequestHandlerSelectors;
  10. import springfox.documentation.schema.ModelRef;
  11. import springfox.documentation.service.*;
  12. import springfox.documentation.spi.DocumentationType;
  13. import springfox.documentation.spi.service.contexts.SecurityContext;
  14. import springfox.documentation.spring.web.plugins.Docket;
  15. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  16. import java.util.ArrayList;
  17. import java.util.List;
  18. @Configuration
  19. @EnableSwagger2
  20. public class SwaggerConfig {
  21. @Bean
  22. public Docket createRestApi() {
  23. return new Docket(DocumentationType.SWAGGER_2)
  24. .apiInfo(apiInfo())
  25. .select()
  26. .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
  27. .paths(PathSelectors.any())
  28. .build()
  29. .globalOperationParameters(setHeaderToken());
  30. }
  31. private ApiInfo apiInfo() {
  32. return new ApiInfoBuilder()
  33. .title("Swagger API")
  34. .description("test")
  35. .termsOfServiceUrl("")
  36. .contact(new Contact("wd", "", ""))
  37. .version("2.0")
  38. .build();
  39. }
  40. private List<ApiKey> securitySchemes() {
  41. List<ApiKey> apiKeyList = new ArrayList();
  42. apiKeyList.add(new ApiKey("token", "token", "header"));
  43. return apiKeyList;
  44. }
  45. private ApiKey apiKey() {
  46. return new ApiKey("token", "token", "header");
  47. }
  48. private List<Parameter> setHeaderToken() {
  49. ParameterBuilder tokenPar = new ParameterBuilder();
  50. List<Parameter> pars = new ArrayList<>();
  51. tokenPar.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
  52. pars.add(tokenPar.build());
  53. return pars;
  54. }
  55. }

参考:

spring-boot swagger2 设置全局token,说明页面接口无法带入token https://www.cnblogs.com/webttt/p/12016135.html

SpringBoot2 配置swagger2并统一加入认证参数 https://www.jianshu.com/p/7a24d202b395

Springboot Oauth2 集成Swagger2权限验证实战 https://www.cnblogs.com/entfrm/p/12751262.html

https://gitee.com/wxdfun/sw.git

https://github.com/SpringForAll/spring-boot-starter-swagger.git

https://didispace-wx.blog.csdn.net/article/details/107438093

https://www.jianshu.com/p/aaab36790743

https://blog.csdn.net/lk1822791193/article/details/106540734

https://blog.csdn.net/ttzommed/article/details/81103609

https://www.jianshu.com/p/09eaa3bab2bb

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/519028
推荐阅读
相关标签
  

闽ICP备14008679号