2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【応用編】Spring Cloud GatewayでAPIゲートウェイを作ってみる -IP制御-

Posted at

🧭 はじめに

API Gatewayは、外部からのアクセスを一元管理する重要なコンポーネントです。セキュリティ強化の一環として、特定のIPアドレスからのアクセスを制限する「IP制御」は非常に有効です。

本記事では、Spring Cloud GatewayでIPアドレスによるアクセス制御を行う方法を紹介します。


🧩 システム構成図


⚙️ IP制御の方法

Spring Cloud Gatewayでは、RemoteAddr プレディケートを使ってIP制限が可能です。

application.yml の例

spring:
  cloud:
    gateway:
      routes:
        - id: allow-specific-ip
          uri: http://localhost:8081
          predicates:
            - Path=/api/**
            - RemoteAddr=192.168.1.100/32

説明

  • RemoteAddr=192.168.1.100/32
    → この設定により、192.168.1.100 のIPアドレスからのアクセスのみ許可されます。

🧪 複数IPの許可

複数のIPを許可したい場合は、複数の RemoteAddr プレディケートを使うか、カスタムフィルターを作成します。

複数の RemoteAddr プレディケート例(yaml)

Spring Cloud Gateway では、1つのルートに複数の RemoteAddr プレディケートを直接指定することはできません。そのため、複数のルートを定義することで、複数のIPアドレスを許可する構成にします。

spring:
  cloud:
    gateway:
      routes:
        - id: allow-ip-1
          uri: http://localhost:8081
          predicates:
            - Path=/api/**
            - RemoteAddr=192.168.1.100/32

        - id: allow-ip-2
          uri: http://localhost:8081
          predicates:
            - Path=/api/**
            - RemoteAddr=10.0.0.5/32

カスタムフィルター例(Java)

public class IpFilter implements GatewayFilter {

    private final List<String> allowedIps = List.of("192.168.1.100", "10.0.0.5");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
        if (!allowedIps.contains(ip)) {
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
}

🔄 動的なIP制御(RedisやDB連携)

IPリストをRedisやDBに保存し、動的に読み込むことで柔軟な制御が可能です。

RedisからIPリストを取得する例(擬似コード)

List<String> allowedIps = redisTemplate.opsForList().range("allowed_ips", 0, -1);

✅ まとめ

Spring Cloud Gatewayでは、IPアドレスによるアクセス制御を簡単に実装できます。静的な設定だけでなく、動的なフィルターを使うことで、より柔軟なセキュリティ対策が可能です。


📎 参考リンク

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?