Spring Cloud Gateway 使用谓词检查头部授权

Posted

技术标签:

【中文标题】Spring Cloud Gateway 使用谓词检查头部授权【英文标题】:Spring Cloud Gateway Use predicate to check header authorization 【发布时间】:2020-09-05 19:45:40 【问题描述】:

是否可以使用 spring 云网关配置的谓词部分来检查标头授权,我的目标是在一个或多个端点上进行一些基本的身份验证

我正在使用 application.yml 进行路由配置

cloud:
gateway:
  routes:
    - id: serviceRoute
      uri: http://service:8000
      predicates:
        - Path=/service/
        **- Header= ??** 
      filters:
        - name: CircuitBreaker
          args:
            name: slow
            fallbackUri: forward:/fallback/service

【问题讨论】:

【参考方案1】:

找出语法,只有在两个条件都满足时才会路由到服务

cloud:
gateway:
  routes:
    - id: serviceRoute
      uri: http://service:8000
      predicates:
        - Path=/service/
        - Header=Authorization, Basic password
      filters:
        - name: CircuitBreaker
          args:
            name: slow
            fallbackUri: forward:/fallback/service

【讨论】:

可以添加java配置吗?【参考方案2】:

以下是我基于spring gateway sample 的示例。如果没有授权头,访问http://localhost:20000/,响应码是404。如果添加授权,响应码是405,表示可以访问。请根据需要更改路径。

主类定义

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.SecurityWebFilterChain;

@SpringBootApplication
public class DemogatewayApplication 

    @Bean
    SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception 
        return http.httpBasic().and()
                .csrf().disable()
                .authorizeExchange()
                .pathMatchers("/anything/**").authenticated()
                .anyExchange().permitAll()
                .and()
                .build();
    

    @Bean
    public MapReactiveUserDetailsService reactiveUserDetailsService() 
        UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build();
        return new MapReactiveUserDetailsService(user);
    

    public static void main(String[] args) 
        SpringApplication.run(DemogatewayApplication.class, args);
    


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>spring-cloud-gateway-sample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-cloud-gateway-sample</name>
    <description>Demo project for Spring Cloud Gateway</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.RC2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>$spring-cloud.version</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

application.yml 定义


server:
  port: 20000

spring:
  cloud:
    gateway:
      routes:
      - id: serviceRoute
        uri: http://www.sohu.com
        predicates:
        - Path=/
        - Header=Authorization, Bearer [0-9a-zA-Z-.]*

【讨论】:

以上是关于Spring Cloud Gateway 使用谓词检查头部授权的主要内容,如果未能解决你的问题,请参考以下文章

Spring Cloud Alibaba - 26 Gateway-自定义谓词工厂

如何使用Spring Cloud Gateway,99%的人都不知道!

Spring Cloud Alibaba - 25 Gateway-路由断言工厂Route Predicate Factories谓词工厂示例及源码解析

Spring Cloud Gateway 和 DiscoveryClient 路由

003-spring cloud gateway-概述基本原理Route Predicate Factory

SpringCloud gateway谓词