| | |
| | | .select() |
| | | .apis(RequestHandlerSelectors.basePackage("com.linghu.controller")) |
| | | .paths(PathSelectors.any()) |
| | | .build() |
| | | .build(); |
| | | // 重点修改:使用 securitySchemes + securityContext 替代全局参数 |
| | | .securitySchemes(Arrays.asList(apiKey())) // 添加安全方案 |
| | | .securityContexts(Arrays.asList(securityContext())); // 应用安全上下文 |
| | | // .securitySchemes(Arrays.asList(apiKey())) // 添加安全方案 |
| | | // .securityContexts(Arrays.asList(securityContext())); // 应用安全上下文 |
| | | } |
| | | |
| | | // 1. 定义安全方案(在Swagger UI顶部添加Authorize按钮) |
| | | private ApiKey apiKey() { |
| | | return new ApiKey("BearerToken", "Authorization", "header"); |
| | | } |
| | | |
| | | // 2. 配置安全上下文(全局生效) |
| | | private SecurityContext securityContext() { |
| | | return SecurityContext.builder() |
| | | .securityReferences(defaultAuth()) |
| | | .forPaths(PathSelectors.any()) // 对所有路径生效 |
| | | .build(); |
| | | } |
| | | |
| | | // 3. 设置默认授权范围 |
| | | private List<SecurityReference> defaultAuth() { |
| | | AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); |
| | | AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; |
| | | authorizationScopes[0] = authorizationScope; |
| | | return Arrays.asList(new SecurityReference("BearerToken", authorizationScopes)); |
| | | } |
| | | // private ApiKey apiKey() { |
| | | // return new ApiKey("BearerToken", "Authorization", "header"); |
| | | // } |
| | | // |
| | | // // 2. 配置安全上下文(全局生效) |
| | | // private SecurityContext securityContext() { |
| | | // return SecurityContext.builder() |
| | | // .securityReferences(defaultAuth()) |
| | | // .forPaths(PathSelectors.any()) // 对所有路径生效 |
| | | // .build(); |
| | | // } |
| | | // |
| | | // // 3. 设置默认授权范围 |
| | | // private List<SecurityReference> defaultAuth() { |
| | | // AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); |
| | | // AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; |
| | | // authorizationScopes[0] = authorizationScope; |
| | | // return Arrays.asList(new SecurityReference("BearerToken", authorizationScopes)); |
| | | // } |
| | | //http://localhost:8080/swagger-ui.html |
| | | private ApiInfo apiInfo() { |
| | | return new ApiInfoBuilder() |