Springcloud Gateway - Gateway assertion factory and filter details and configuration of cross-domain issues

Springcloud-Gateway Gateway assertion factory and filter details and configuration of cross-domain issues

3.3 Route Predicate Factory

3.3.1 Eleven basic Predicate factories provided by Spring (official documents can be consulted, no need to memorize them by rote)

insert image description here

3.3.2 Take After as an example to demonstrate the assertion factory

Configure the routing assertion of orderservice, After can only be accessed at the specified time

- id: order-service #路由id 可自定义但要保证唯一性
  uri: lb://orderservice #路由的目标地址
  predicates: #判断请求是否符合路由规则的条件
    - Path=/order/**
    - After=2031-04-13T15:14:47.433+08:00[Asia/Shanghai]

After setting the assertion factory, if the assertion rules are not met, accessing the orderservice through the gateway reports 404
insert image description here

Set After to before to successfully access

Before=2031-04-13T15:14:47.433+08:00[Asia/Shanghai]

insert image description here

3.4 Route filter GatewayFilter

3.4.1 When users request gateway services, they first enter the route, and then go through a series of filter chains (as shown in the figure)

insert image description here

3.4.2 Take AddRequestHeader as an example to demonstrate

Add a request header to all requests entering userservice: Springcloud 666

1. Modify the application.yml file in the gateway and add a filter to the userservice route

- id: user-service #路由id 可自定义但要保证唯一性
  uri: lb://userservice #路由的目标地址
  predicates: #判断请求是否符合路由规则的条件
   - Path=/user/**
  filters:
    - AddRequestHeader=Truth,springcloud 666

2. springmvc gets the request header

@GetMapping("/{id}")
public User queryById(@PathVariable("id") Long id ,
                      @RequestHeader (value = "Truth",required = false)String truth) {
    
    
    System.out.println(truth);
    return userService.queryById(id);
}

3. Successfully obtained the request header

insert image description here

4. Configure the same filter for all microservices, you can use default-filters (note that the previous filter has been annotated at this time)

  routes: #网关的路由配置
        - id: user-service #路由id 可自定义但要保证唯一性
          uri: lb://userservice #路由的目标地址
          predicates: #判断请求是否符合路由规则的条件
           - Path=/user/**
#          filters:
#            - AddRequestHeader=Truth,springcloud 666
        - id: order-service #路由id 可自定义但要保证唯一性
          uri: lb://orderservice #路由的目标地址
          predicates: #判断请求是否符合路由规则的条件
            - Path=/order/**
            - Before=2031-04-13T15:14:47.433+08:00[Asia/Shanghai]
      default-filters:
        - AddRequestHeader=Truth,springcloud 666!

5. The request header can still be obtained successfully, indicating that the default filter is also in effect

insert image description here

3.4.3 GlobalFilter

1. The function of the global filter is also to process all the requests and microservice responses entering the gateway. It has the same function as the GatewayFilter, but there are differences between the two. The difference lies in

GatewayFilter is defined by configuration files, which is suitable for processing some logically fixed responses, while the logic of GlobalFilter needs to be implemented by writing code yourself, which is more flexible

2. Customized way, by implementing the GlobalFilter interface to achieve a global filter to achieve a simple login authentication

@Component
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    
    
        //获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //获取参数中的authorization参数
        String authorization = queryParams.getFirst("authorization");
        //判断参数值是否等于admin
        if ("admin".equals(authorization)) {
    
    
            //是就放行
            return chain.filter(exchange);
        }
        //设置响应状态码401表示用户未登录
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //拦截
        return exchange.getResponse().setComplete();

    }
}

3. When there is no request parameter, a 401 status code is reported, indicating that you are not logged in

insert image description here

4. When there are request parameters, the data is successfully obtained

insert image description here

3.4.4 Execution order of filters

3.4.4.1 Types of Route Filters

When a request enters the gateway, it will encounter three types of filters: current route filter, DefaultFilter, GlobalFilter

After requesting routing, the current routing filter, DefaultFilter, and GlobalFilter will be merged into a filter chain (that is, a collection), and each filter will be executed in turn after sorting

insert image description here

3.4.4.2 Execution order

Each filter must specify an int type order value, the smaller the order value, the higher the priority, and the higher the execution order.

GlobalFilter specifies the order value by implementing the Ordered interface or adding the @Order annotation, which is specified by ourselves

The order of routing filters and defaultFilter is specified by Spring, and the default is to increase from 1 according to the order of declaration.

When the order values ​​of the filters are the same, they will be executed in the order of defaultFilter > routing filter > GlobalFilter.

3.5 Cross-domain problem solving

3.5.1 Definition of cross-domain

Inconsistent domain names are cross-domain, mainly including:

Different domain names: www.taobao.com and www.taobao.org and www.jd.com and miaosha.jd.com

Same domain name, different ports: localhost:8080 and localhost8081

Cross-domain problem: The browser prohibits the originator of the request from making a cross-domain ajax request with the server, and the request is intercepted by the browser

(Note that the browser's ajax request is normally sent to the server, but the server fails to respond)

Solution: CORS configuration

spring:
  cloud:
    gateway:
      globalcors: # 全局的跨域处理
        add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
        corsConfigurations:
          '[/**]':
            allowedOrigins: # 允许哪些网站的跨域请求
              - "http://localhost:8090"
              - "http://www.leyou.com"
            allowedMethods: # 允许的跨域ajax的请求方式
              - "GET"
              - "POST"
              - "DELETE"
              - "PUT"
              - "OPTIONS"
            allowedHeaders: "*" # 允许在请求中携带的头信息
            allowCredentials: true # 是否允许携带cookie
            maxAge: 360000 # 这次跨域检测的有效期






















































Guess you like

Origin blog.csdn.net/weixin_64133130/article/details/130296037