Backend Development 6 min read

Implementing Internal/External API Access Control with Gateway, Redis Whitelist, and AOP in Spring Cloud

This article explains three practical approaches—microservice isolation, Redis‑based whitelist, and gateway‑AOP header checks—to restrict APIs to internal calls only, and provides detailed Spring Cloud code examples for the preferred AOP solution.

Architecture Digest
Architecture Digest
Architecture Digest
Implementing Internal/External API Access Control with Gateway, Redis Whitelist, and AOP in Spring Cloud

When a business requirement demands that certain interfaces be callable only within the internal network and not exposed externally, developers have several viable strategies. This article first outlines three possible solutions and then demonstrates a concrete implementation using Spring Cloud Gateway and AOP.

Solution 1: Microservice Isolation – Deploy external‑exposed APIs and internal‑only APIs in separate microservices, routing external traffic to one service and internal traffic to another. While clear in separation, it adds extra services, increases latency, and raises maintenance overhead.

Solution 2: Gateway + Redis Whitelist – Store a whitelist of allowed internal APIs in Redis; the gateway checks each request against this list, allowing or rejecting it. This approach requires no code changes but incurs ongoing whitelist management effort and adds per‑request latency.

Solution 3: Gateway + AOP Header Check (Preferred) – The gateway adds a custom header (e.g., from: public ) to external requests. Backend services use an AOP aspect to inspect this header; if the header is present, the request is considered external and may be blocked for internal‑only endpoints. This distributes access control to each service, reduces gateway load, and improves response speed, though it introduces a small amount of code intrusion that can be mitigated with annotations.

Implementation Details

First, configure the gateway to append the header:

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono
filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(
            exchange.mutate().request(
                exchange.getRequest().mutate()
                    .header("id", "")
                    .header("from", "public")
                    .build())
            .build()
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

Next, create an AOP aspect and a custom annotation to enforce internal‑only access:

@Aspect
@Component
@Slf4j
public class OnlyIntranetAccessAspect {
    @Pointcut("@within(org.openmmlab.platform.common.annotation.OnlyIntranetAccess)")
    public void onlyIntranetAccessOnClass() {}

    @Pointcut("@annotation(org.openmmlab.platform.common.annotation.OnlyIntranetAccess)")
    public void onlyIntranetAccessOnMethod() {}

    @Before("onlyIntranetAccessOnMethod() || onlyIntranetAccessOnClass()")
    public void before() {
        HttpServletRequest hsr = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String from = hsr.getHeader("from");
        if (!StringUtils.isEmpty(from) && "public".equals(from)) {
            log.error("This api is only allowed invoked by intranet source");
            throw new MMException(ReturnEnum.C_NETWORK_INTERNET_ACCESS_NOT_ALLOWED_ERROR);
        }
    }
}

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OnlyIntranetAccess {}

Finally, annotate any internal‑only endpoint with @OnlyIntranetAccess :

@GetMapping("/role/add")
@OnlyIntranetAccess
public String onlyIntranetAccess() {
    return "该接口只允许内部服务调用";
}

The article concludes that this AOP‑based method provides a flexible, low‑impact way to enforce internal API access while keeping business logic clear.

microservicesAOPBackend DevelopmentRedisAccess ControlAPI GatewaySpring Cloud
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.