时间:2021-05-20
引入依赖
自定义过滤器
可以继承 AbstractGatewayFilterFactory 或实现 GlobalFilter 实现过滤请求功能
GatewayFilter
GatewayFilter 只能指定路径上应用
import org.springframework.cloud.gateway.filter.GatewayFilter;import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;import org.springframework.http.HttpStatus;import org.springframework.http.server.reactive.ServerHttpResponse;import org.springframework.stereotype.Component;@Componentpublic class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<AuthGatewayFilterFactory.Config> { public AuthGatewayFilterFactory() { super(Config.class); } @Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { System.out.println("Welcome to AuthFilter."); String token = exchange.getRequest().getHeaders().getFirst("sign"); if (Config.secret.equals(token)) { return chain.filter(exchange); } ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); return response.setComplete(); }; } static class Config { static String secret = "1234"; }}spring: cloud: gateway: routes: - id: service2_route uri: http://127.0.0.1:8082 predicates: - Path=/s2/** filters: - StripPrefix=1 # 去掉路径的 n 个前缀 - Auth=true # 输入过滤器类的名称前缀GlobalFilter
GlobalFilter 可以在全局应用
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.http.server.reactive.ServerHttpRequest;import org.springframework.http.server.reactive.ServerHttpResponse;import org.springframework.stereotype.Component;import org.springframework.web.server.ServerWebExchange;import reactor.core.publisher.Mono;@Componentpublic class AuthGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { System.out.println("Welcome to AuthGlobalFilter."); ServerHttpRequest request = exchange.getRequest(); String sign = request.getHeaders().get("sign").get(0); String token = "1234"; if(token.equals(sign)) { return chain.filter(exchange); } ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); return response.setComplete(); } @Override public int getOrder() { return 0; }}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
springcloudgateway的包结构(在Idea2019.3中展示)这个包是spring-cloud-gateway-core.这里是真正的spring
在Spring-Cloud-Gateway之请求处理流程文中我们了解最终网关是将请求交给过滤器链表进行处理,接下来我们阅读Spring-Cloud-Gatewa
1.官方文档https://cloud.spring.io/spring-cloud-static/spring-cloud-openfeign/2.2.2.R
文档地址https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-ali
SpringBoot下token短信验证登入登出(token存放redis)不对SpringBoot进行介绍,具体的可以参考官方文档介绍:token基本使用,r