このバージョンはまだ開発中であり、まだ安定しているとは見なされていません。最新の安定バージョンについては、Spring Cloud Gateway 5.0.3 を使用してください!

Spring Security 統合

Spring Cloud Gateway サーバーと WebFlux は、Spring Security と連携して経路を保護し、トークンを下流サービスに中継します。

依存関係

ゲートウェイに Spring Security を追加するには、以下のスターターを 1 つ以上含めてください。

pom.xml
<!-- Core security (authentication and authorization) -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- OAuth2 login and token relay to downstream services -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

<!-- Resource server: validate JWT or opaque tokens on each request -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

デフォルトの動作

spring-boot-starter-security がクラスパス上にある場合、Spring Boot はすべてのリクエストに認証をリクエストする SecurityWebFilterChain を自動的に構成します。特定のパスを開放したり、カスタムルールを適用したりするには、明示的に SecurityWebFilterChain Bean を指定する必要があります。

次の例では、認証なしでヘルスチェックエンドポイントを許可し、その他のすべてのリクエストには有効な JWT をリクエストします。

RouteSecurityConfiguration.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
@EnableWebFluxSecurity
public class RouteSecurityConfiguration {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        return http
                .authorizeExchange(exchanges -> exchanges
                        .pathMatchers("/actuator/health/**").permitAll()
                        .anyExchange().authenticated())
                .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
                .build();
    }
}

トークンリレー

ゲートウェイが OAuth2 クライアントとして動作する場合、現在認証されているユーザーのアクセストークンを下流サービスに転送できます。使用方法と必要な依存関係については、TokenRelay ゲートウェイフィルターファクトリのドキュメントを参照してください。

参考文献

SecurityWebFilterChain、メソッドのセキュリティ、OAuth2 統合の詳細については、Spring Security リアクティブ型 Web アプリケーションのリファレンスを参照してください。