【SpringClooud】SpringCloud-Gateway聚合Swagger2文档(七)

文章目录

  • Note
  • Github
  • Code
    • SwaggerAPI配置
    • Gateway新增SwaggerAPI聚合配置
    • Gateway对外提供Swagger资源
    • 如果配置了Oauth2认证授权,需要开放Swagger的资源

Note

Github

地址:https://github.com/ithuhui/hui-cloud-platform
模块:【Any-Service】
分支:master

Code

SwaggerAPI配置

每个需要提供API的都需要配置(User-Service / Schedule-Service / Auth-service)

/**
 * AuthServerConfig
 * 

* Description: *

* Creation Time: 2019/3/12 22:39. * * @author HuWeihui */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { // 构建授权参数在请求头 ParameterBuilder parBuilder = new ParameterBuilder(); List<Parameter> pars = new ArrayList<Parameter>(); Parameter authorizationParameter = parBuilder.name("Authorization") .description("授权TOKEN") .modelRef(new ModelRef("string")) .parameterType("header").required(false).build(); pars.add(authorizationParameter); StopWatch watch = new StopWatch(); watch.start(); Docket swaggerSpringMvcPlugin = new Docket(DocumentationType.SWAGGER_2) .groupName("usercenter-service") .apiInfo(apiInfo()) .globalOperationParameters(pars) .useDefaultResponseMessages(false) .select().apis(RequestHandlerSelectors.basePackage("com.hui.cloud.uc")) .paths(PathSelectors.any()) .build(); watch.stop(); return swaggerSpringMvcPlugin; } private ApiInfo apiInfo() { String title = "usercenter-service API文档"; String description = " RESTFUL API"; return new ApiInfoBuilder() .title(title) .description(description) .version("1.0.0") .build(); } }

Gateway新增SwaggerAPI聚合配置


/**
 * SwaggerProvider
 * 

* Description *

* Creation Time: 2019/9/13 0:44. * * @author Hu-Weihui */ @Component @Primary @AllArgsConstructor public class SwaggerProvider implements SwaggerResourcesProvider { public static final String API_URI = "/v2/api-docs"; @Autowired private final RouteLocator routeLocator; @Autowired private final GatewayProperties gatewayProperties; @Override public List<SwaggerResource> get() { List<SwaggerResource> resources = new ArrayList<>(); List<String> routes = new ArrayList<>(); //取出gateway的route routeLocator.getRoutes().subscribe(route -> routes.add(route.getId())); //结合配置的route-路径(Path),和route过滤,只获取有效的route节点 gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId())) .forEach(routeDefinition -> routeDefinition.getPredicates().stream() .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName())) .forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0") // 注意我的swagger配置了 group 所以传参新增 ?group=serviceId .replace("/**", API_URI+"?group="+routeDefinition.getId()))))); 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; } }

Gateway对外提供Swagger资源

/**
 * SwaggerHandler
 * 
 * 描述:
 * 
 * Creation Time: 2019/10/4 18:13.
 *
 * @author Gary.Hu
 */
@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() {
     
        return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
    }
}

如果配置了Oauth2认证授权,需要开放Swagger的资源

/**
 * ResourceServerConfig
 * 
 * 描述:资源服务配置
 * 
 * Creation Time: 2019/10/1 1:38.
 *
 * @author Gary.Hu
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
     

    private TokenStore tokenStore;

    @Autowired
    public ResourceServerConfig(TokenStore tokenStore) {
     
        this.tokenStore = tokenStore;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
     
        http
                .csrf().disable()
                .authorizeRequests()
                //swagger放行
                .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/v2/**").permitAll()
                .antMatchers("/usercenter-service/**").permitAll()
                //允许登录、注册放行
                .antMatchers("/sys-user/user","/sys-user/login","/sys-user/register","/h2-console").permitAll()
                // 健康检查放行
                .antMatchers("/actuator/**").permitAll()
                //OPTIONS请求 放行
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .anyRequest().authenticated();

    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
     
        resources
                .tokenStore(tokenStore)
                // 设置资源ID
                .resourceId("usercenter-service");
    }
}

你可能感兴趣的:(SpringCloud,Springcloud,gateway,swagger)