springcloud2 gateway 之一:简单样例
https://blog.csdn.net/haveqing/article/details/88424598

springcloud2 gateway 之二:转发调用eureka客户端服务
https://blog.csdn.net/haveqing/article/details/88427571

文件结构

一、GatewayConfig.java

package com.urthink.upfs.springcloudgateway.config;

import com.urthink.upfs.springcloudgateway.filter.TokenFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GatewayConfig {

    @Bean
    public TokenFilter tokenFilter(){
        return new TokenFilter();
    }
}

二、TokenFilter.java

每一个GlobalFilter都作用在每一个router上,能够满足大多数的需求。但是如果遇到业务上的定制,可能需要编写满足自己需求的GlobalFilter。在下面的案例中将讲述如何编写自己GlobalFilter,该GlobalFilter会校验请求中是否包含了请求参数“token”,如何不包含请求参数“token”则不转发路由,否则执行正常的逻辑。代码如下:

package com.urthink.upfs.springcloudgateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * gateway全局过滤器
 * https://blog.csdn.net/forezp/article/details/85057268
 */
public class TokenFilter implements GlobalFilter, Ordered {

    Logger logger= LoggerFactory.getLogger( TokenFilter.class );
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (token == null || token.isEmpty()) {
            logger.info( "token is empty..." );
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}

在上面的TokenFilter需要实现GlobalFilter和Ordered接口,这和实现GatewayFilter很类似。然后根据ServerWebExchange获取ServerHttpRequest,然后根据ServerHttpRequest中是否含有参数token,如果没有则完成请求,终止转发,否则执行正常的逻辑。

三、访问

http://localhost:8080/app2/demo/test1

返回 401 Unauthorized

http://localhost:8080/app2/demo/test1?token=tokendata

正常返回数据

 

既然gateway已经连接到eureka,就可以通过feign调用其他服务,做更复杂的权限验证了,而不必直接连数据库。

 

参考:

spring cloud gateway之filter篇
https://blog.csdn.net/forezp/article/details/85057268

Spring-Cloud-Gateway之过滤器GatewayFilter
https://www.jianshu.com/p/eb3a67291050

spring cloud gateway 2 深入了解 - filter
https://www.jianshu.com/p/5e40bbc95eb9

微服务架构spring cloud - Gateway过滤器(十二)
https://blog.csdn.net/m0_37834471/article/details/82621337

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐