SpringCloudGateway⽹关集成Swagger2.9.2设置全局token
正常使⽤时,我们的接⼝需要登陆才能访问的。即登录时,要传⼀个登陆后的token才能访问的。
那这个怎么设置,才可以让所有接⼝都允许登陆后访问呢。
设置全局token解决办法如下:
1. 在pom中加⼊依赖
<properties>
<swagger.version>2.9.2</swagger.version>
</properties>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 2.9.2中默认使⽤的是 swagger-models-1.5.20 版本,该版本中的example只判断了值是否为空,但是并没有判断值是否是空串,映射上就会报 NumberForm <dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
2. swagger配置如下
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket platformApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).forCodeGeneration(true)
.select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.apis(RequestHandlerSelectors.any())
.paths(regex("^.*(?<!error)$"))
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList = new ArrayList();
apiKeyList.add(new ApiKey("token", "token", "header"));
return apiKeyList;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts=new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.("^(?!auth).*$"))
.
build());
return securityContexts;
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("token", authorizationScopes));//验证增加(有许多教程说明中这个地⽅是Authorization,导致不能带⼊全局toke return securityReferences;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("接⼝⽂档")
.description("⽤于说明接⼝使⽤")
.contact(new Contact("csruan", "", ""))
.license("Apache License Version 2.0")
.version("1.0").build();
}
}
3. ⽹关中增加配置
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
publisher.Mono;
import springfox.documentation.swagger.web.*;
import java.util.Optional;
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerHandler {
@Autowired(required = false)
private SecurityConfiguration securityConfiguration;
@Autowired(required = false)
private UiConfiguration uiConfiguration;
private final SwaggerResourcesProvider swaggerResources;
@Autowired
public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
this.swaggerResources = swaggerResources;
}
@GetMapping("/configuration/security")
public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK)); }
@GetMapping("/configuration/ui")
public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("")
public Mono<ResponseEntity> swaggerResources() {
reference groupreturn Mono.just((new ResponseEntity<>((), HttpStatus.OK)));
}
}
import lombok.AllArgsConstructor;
import org.springframework.fig.GatewayProperties;
import org.springframework.ute.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import t.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
/**
* 聚合接⼝⽂档注册
*/
@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {
public static final String API_URI = "/v2/api-docs";
private final RouteLocator routeLocator;
private final GatewayProperties gatewayProperties;
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
List<String> routes = new ArrayList<>();
//取出gateway的route
//结合配置的route-路径(Path),和route过滤,只获取有效的route节点
.filter(predicateDefinition -> ("Path").Name()))
.forEach(predicateDefinition -> resources.add(Id(),
.replace("/**", API_URI)))));
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion("2.0");
return swaggerResource;
}
}
4. yml
spring:
application:
name: gateway # 服务名称
cloud:
nacos:
discovery:
server-addr: localhost:8848 # 注册中⼼地址 # 默认是没有密码的
gateway:
discovery:
locator:
enabled: true #表明gateway开启服务注册和发现的功能,动态路由
lowerCaseServiceId: true
filters:
routes:
- id: test # 唯⼀id ,随便起,不能重复
uri: lb://test # 匹配注册中⼼的服务
predicates:
- Path=/test/** # 匹配的规则
filters:
# 去掉路由前缀,访问 localhost:8088/test/v2/api 转发的就是 localhost:8089/v2/api
# 1 : 代表剥离路径的个数
- StripPrefix=1
特别注意:-StripPrefix=1,这个⼀定不要去掉,不然你就访问不到你服务的swagger,如下图
以上步骤完成,已经在⽹关中集成了swagger,并可以全局添加token。
下⾯说明给所有单个接⼝添加token,swagger配置如下:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论