|
| 1 | +package com.love.yourvoiceback.common.config; |
| 2 | + |
| 3 | +import io.swagger.v3.oas.models.Components; |
| 4 | +import io.swagger.v3.oas.models.OpenAPI; |
| 5 | +import io.swagger.v3.oas.models.Operation; |
| 6 | +import io.swagger.v3.oas.models.PathItem; |
| 7 | +import io.swagger.v3.oas.models.security.SecurityRequirement; |
| 8 | +import io.swagger.v3.oas.models.security.SecurityScheme; |
| 9 | +import org.springdoc.core.customizers.OpenApiCustomizer; |
| 10 | +import org.springframework.context.annotation.Bean; |
| 11 | +import org.springframework.context.annotation.Configuration; |
| 12 | + |
| 13 | +@Configuration |
| 14 | +public class OpenApiConfig { |
| 15 | + |
| 16 | + private static final String ACCESS_TOKEN_SCHEME = "accessToken"; |
| 17 | + |
| 18 | + @Bean |
| 19 | + public OpenAPI openAPI() { |
| 20 | + return new OpenAPI() |
| 21 | + .components(new Components() |
| 22 | + .addSecuritySchemes( |
| 23 | + ACCESS_TOKEN_SCHEME, |
| 24 | + new SecurityScheme() |
| 25 | + .name(ACCESS_TOKEN_SCHEME) |
| 26 | + .type(SecurityScheme.Type.HTTP) |
| 27 | + .scheme("bearer") |
| 28 | + .bearerFormat("JWT") |
| 29 | + )); |
| 30 | + } |
| 31 | + |
| 32 | + @Bean |
| 33 | + public OpenApiCustomizer securedApiCustomizer() { |
| 34 | + return openApi -> { |
| 35 | + if (openApi.getPaths() == null) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + openApi.getPaths().forEach((path, pathItem) -> { |
| 40 | + if (isPublicPath(path) || pathItem == null) { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + applySecurity(pathItem.getGet()); |
| 45 | + applySecurity(pathItem.getPost()); |
| 46 | + applySecurity(pathItem.getPut()); |
| 47 | + applySecurity(pathItem.getPatch()); |
| 48 | + applySecurity(pathItem.getDelete()); |
| 49 | + applySecurity(pathItem.getHead()); |
| 50 | + applySecurity(pathItem.getOptions()); |
| 51 | + applySecurity(pathItem.getTrace()); |
| 52 | + }); |
| 53 | + }; |
| 54 | + } |
| 55 | + |
| 56 | + private boolean isPublicPath(String path) { |
| 57 | + return path.startsWith("/auth"); |
| 58 | + } |
| 59 | + |
| 60 | + private void applySecurity(Operation operation) { |
| 61 | + if (operation == null) { |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + if (operation.getSecurity() == null || operation.getSecurity().isEmpty()) { |
| 66 | + operation.addSecurityItem(new SecurityRequirement().addList(ACCESS_TOKEN_SCHEME)); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments