You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.6 KiB

5 months ago
  1. package com.qyft.ms.system.config;
  2. import cn.hutool.core.util.ArrayUtil;
  3. import io.swagger.v3.oas.models.Components;
  4. import io.swagger.v3.oas.models.OpenAPI;
  5. import io.swagger.v3.oas.models.info.Info;
  6. import io.swagger.v3.oas.models.security.SecurityRequirement;
  7. import io.swagger.v3.oas.models.security.SecurityScheme;
  8. import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.http.HttpHeaders;
  12. import org.springframework.util.AntPathMatcher;
  13. import java.util.stream.Stream;
  14. /***
  15. * 创建Swagger配置
  16. */
  17. @Configuration
  18. public class SwaggerConfig {
  19. @Bean
  20. public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() {
  21. return openApi -> {
  22. // 全局添加Authorization
  23. if (openApi.getPaths() != null) {
  24. openApi.getPaths().forEach((path, pathItem) -> {
  25. // 忽略认证的请求无需携带 Authorization
  26. String[] ignoreUrls = {"/api/auth/login"};
  27. if (ArrayUtil.isNotEmpty(ignoreUrls)) {
  28. // Ant 匹配忽略的路径,不添加Authorization
  29. AntPathMatcher antPathMatcher = new AntPathMatcher();
  30. if (Stream.of(ignoreUrls).anyMatch(ignoreUrl -> antPathMatcher.match(ignoreUrl, path))) {
  31. return;
  32. }
  33. }
  34. // 其他接口统一添加Authorization
  35. pathItem.readOperations()
  36. .forEach(operation ->
  37. operation.addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION))
  38. );
  39. });
  40. }
  41. };
  42. }
  43. @Bean
  44. public OpenAPI customOpenAPI() {
  45. return new OpenAPI()
  46. .info(new Info()
  47. .title("基质喷涂")
  48. .version("1.0")) // 配置全局鉴权参数-Authorize
  49. .components(new Components()
  50. .addSecuritySchemes(HttpHeaders.AUTHORIZATION,
  51. new SecurityScheme()
  52. .name(HttpHeaders.AUTHORIZATION)
  53. .type(SecurityScheme.Type.APIKEY)
  54. .in(SecurityScheme.In.HEADER)
  55. .scheme("Bearer")
  56. .bearerFormat("JWT")
  57. )
  58. );
  59. }
  60. }