|
| 1 | +package dev.nano.gateway.security; |
| 2 | + |
| 3 | +import org.springframework.beans.factory.annotation.Autowired; |
| 4 | +import org.springframework.beans.factory.annotation.Qualifier; |
| 5 | +import org.springframework.cloud.gateway.filter.GatewayFilterChain; |
| 6 | +import org.springframework.cloud.gateway.filter.GlobalFilter; |
| 7 | +import org.springframework.cloud.gateway.route.Route; |
| 8 | +import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; |
| 9 | +import org.springframework.context.annotation.Lazy; |
| 10 | +import org.springframework.core.Ordered; |
| 11 | +import org.springframework.http.HttpStatus; |
| 12 | +import org.springframework.stereotype.Component; |
| 13 | +import org.springframework.web.server.ResponseStatusException; |
| 14 | +import org.springframework.web.server.ServerWebExchange; |
| 15 | +import reactor.core.publisher.Mono; |
| 16 | + |
| 17 | +import java.util.List; |
| 18 | + |
| 19 | +@Component |
| 20 | +public class ApiAuthorizationFilter implements GlobalFilter, Ordered { |
| 21 | + |
| 22 | + final ApiKeyAuthorizationChecker apiKeyAuthorizationChecker; |
| 23 | + |
| 24 | + @Autowired |
| 25 | + public ApiAuthorizationFilter( |
| 26 | + @Qualifier("main-checker") @Lazy ApiKeyAuthorizationChecker apiKeyAuthorizationChecker |
| 27 | + ) { |
| 28 | + this.apiKeyAuthorizationChecker = apiKeyAuthorizationChecker; |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { |
| 33 | + |
| 34 | + Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR); |
| 35 | + String applicationName = route.getId(); |
| 36 | + List<String> apiKey = exchange.getRequest().getHeaders().get("ApiKey"); |
| 37 | + |
| 38 | + if (applicationName == null || apiKey.isEmpty()) { |
| 39 | + throw new ResponseStatusException( |
| 40 | + HttpStatus.UNAUTHORIZED, |
| 41 | + "Application name is not defined, you are not authorized to access this resource" |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + return chain.filter(exchange); |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + public int getOrder() { |
| 50 | + return Ordered.LOWEST_PRECEDENCE; // lowest priority filter |
| 51 | + } |
| 52 | +} |
0 commit comments