|
| 1 | +package com.hrk.apigw.security; |
| 2 | + |
| 3 | + |
| 4 | +import org.springframework.cloud.gateway.filter.GatewayFilterChain; |
| 5 | +import org.springframework.cloud.gateway.filter.GlobalFilter; |
| 6 | +import org.springframework.cloud.gateway.route.Route; |
| 7 | +import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; |
| 8 | +import org.springframework.core.Ordered; |
| 9 | +import org.springframework.http.HttpStatus; |
| 10 | +import org.springframework.stereotype.Component; |
| 11 | +import org.springframework.web.server.ResponseStatusException; |
| 12 | +import org.springframework.web.server.ServerWebExchange; |
| 13 | +import reactor.core.publisher.Mono; |
| 14 | + |
| 15 | +import java.util.List; |
| 16 | + |
| 17 | +@Component |
| 18 | +public record ApiKeyAuthorizationFilter( |
| 19 | + ApiKeyAuthorizationCheckerFakeImpl apiKeyAuthorizationCheckerFakeImpl) implements GlobalFilter, Ordered { |
| 20 | + |
| 21 | + @Override |
| 22 | + public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { |
| 23 | + System.out.println("ApiKeyAuthorizationFilter... checking the key"); |
| 24 | + |
| 25 | + Route attribute = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR); |
| 26 | + String applicationName = attribute != null ? attribute.getId() : null; |
| 27 | + |
| 28 | + List<String> apiKey = exchange.getRequest().getHeaders().get("ApiKey"); |
| 29 | + |
| 30 | + if (applicationName == null || |
| 31 | + (apiKey == null || apiKey.isEmpty()) || |
| 32 | + !apiKeyAuthorizationCheckerFakeImpl.isAuthorized(apiKey.get(0), applicationName) |
| 33 | + ) |
| 34 | + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "you are not authorized"); |
| 35 | + |
| 36 | + System.out.println("API KEY -> " + apiKey); |
| 37 | + return chain.filter(exchange); |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public int getOrder() { |
| 42 | + return Ordered.LOWEST_PRECEDENCE; |
| 43 | + } |
| 44 | +} |
0 commit comments