How to Restrict API Access to Internal Services Using Gateway, Redis, and AOP

Learn three practical strategies to prevent external exposure of specific APIs—isolating them in separate microservices, employing a Redis‑backed whitelist via the gateway, and using gateway‑added headers with AOP annotations—to enforce internal‑only access, complete with Java code examples.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
How to Restrict API Access to Internal Services Using Gateway, Redis, and AOP

When developing business services, you may encounter the requirement that certain interfaces must not be exposed externally and should only be callable between internal services. This article examines three feasible solutions and demonstrates a concrete implementation.

1. Internal‑External Interface Microservice Isolation

Place externally exposed interfaces and internally restricted interfaces in separate microservices. One service exposes all APIs to the outside, while the other aggregates only internal‑only APIs for intra‑network calls. This adds a new microservice for request forwarding, increasing system complexity, latency, and maintenance cost.

2. Gateway + Redis Whitelist Mechanism

Maintain an interface whitelist in Redis. When a request reaches the gateway, the whitelist is consulted; interfaces on the list are allowed, others are rejected. This approach requires no changes to business code, but maintaining the whitelist is a continuous effort, often requiring ticket submissions, and each request incurs a whitelist lookup, adding response latency.

3. Gateway + AOP Approach

Instead of checking a whitelist at the gateway, this method determines the request source and delegates the check to the business side, reducing gateway processing and improving response speed. By adding a header (e.g., from=public) at the gateway, services can inspect the header: if present, the request is external; if absent, it is internal. Business code can then decide whether to allow the call based on the annotation.

Specific Implementation

First, add a header on the gateway to mark external requests:

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> 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 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(value = "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 API that should be internal‑only:

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

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaaopgatewayAPI Security
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

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.