i have an issue when i add authorizations from spring gateway like this
image 1
image 2
when i hit the swagger api
the api key not send to the api, and get error like this
image 3
the log in microservice not detect the api key that i send from gateway
image 4
the code that i have in spring gate way like this
import org.springdoc.core.properties.SwaggerUiConfigParameters;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Objects;
@Configuration
public class SwaggerConfig {
@Bean
public CommandLineRunner openApiGroups(
RouteDefinitionLocator locator,
SwaggerUiConfigParameters swaggerUiConfigParameters) {
return args -> Objects.requireNonNull(locator
.getRouteDefinitions().collectList().block())
.stream()
.map(RouteDefinition::getId)
.filter(id -> id.matches(".*-service"))
.map(id -> id.replace("-service", ""))
.forEach(swaggerUiConfigParameters::addGroup);
}
}
and micro service like this
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI(){
final String API_KEY_HEADER_NAME = "X-API-KEY";
final String securitySchemeName = "ApiKeyAuth";
return new OpenAPI()
.info(new Info().title("API Documentation")
.version("v1")
.description("This is the API documentation for our application.")
.license(new License().name("Apache 2.0").url("https://springdoc.org")))
.addSecurityItem(new SecurityRequirement().addList(API_KEY_HEADER_NAME))
.components(new Components()
.addSecuritySchemes(API_KEY_HEADER_NAME, new SecurityScheme()
.name(API_KEY_HEADER_NAME)
.type(SecurityScheme.Type.APIKEY)
.in(SecurityScheme.In.HEADER)
.name(API_KEY_HEADER_NAME)));
}
}
and the application.yaml in spring gateway like this
server:
port: 5656
spring:
application:
name: api-gateway
cloud:
gateway:
httpclient:
connect-timeout: 10000
response-timeout: 7s
routes:
- id: ms-idm-service
uri: "http://localhost:6992/"
predicates:
- Path=/api/v1/menu/* , /v3/api-docs/ms-idm
- id: ms-master-data-service
uri: "http://localhost:6991/"
predicates:
- Path=/api/v1/role-code/* , /v3/api-docs/ms-master-data
filters:
- AddRequestHeader=X-API-KEY , f098c80f-f140-4f92-9db6-98b47b84c2b7
discovery:
enabled: true
resilience4j:
time limiter:
configs:
default:
timeoutDuration: 7000
cancelRunningFuture: true
logging:
level:
org:
springframework:
cloud.gateway: DEBUG
http.server.reactive: DEBUG
web.reactive: DEBUG
this is the example of microservice controller
@GetMapping
@Operation(summary = "Get All Role Code",security = {@SecurityRequirement(name = "X-API-KEY")})
public ResponseEntity<ApiResponse> getAll(){
List<TRoleCodeResponseDTO> tRoleCodeResponseDTOS = tRoleCodeService.getAll();
return responseBuilderHelper.buildSingleResponse(ResponseEnum.SUCCESS, API_VERSION_1,
Integer.toString(Constants.OK), Constants.GLB_MESSAGE_SUCCESS, tRoleCodeResponseDTOS);
}
anyone have the solution ?
i have try like this and nothing happen
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class ApiKeyAuthorizationFilter implements GatewayFilter {
private static final String API_KEY_PARAM = "f098c80f-f140-4f92-9db6-98b47b84c2b7";
private static final String AUTHORIZATION_HEADER = "Authorization";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String apiKey = exchange.getRequest().getQueryParams().getFirst(API_KEY_PARAM);
if (apiKey != null && !apiKey.isEmpty()) {
HttpHeaders headers = exchange.getRequest().getHeaders();
headers.set(AUTHORIZATION_HEADER, "Bearer " + apiKey);
return chain.filter(exchange);
}
return Mono.error(new NullPointerException());
}
}