两只角的蜗牛
2022-09-20 20:12:02浏览 1281
课程章节:第7章-局部过滤器 - 校验 Header 中的 Token
课程讲师:张勤一
课程内容:
1. 局部过滤器 - 校验 Header 中的 Token
- 首先定义一个实现GatewayFilter和Ordered的接口的过滤器类,实现其中的filter和getOrder方法。
- 将过滤器类添加到过滤器工厂中。
- 配置信息路由规则(待完善)
1.1 定义过滤器类
package com.imooc.ecommerce.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Slf4j
@Component
public class HeaderTokenGatewayFilter implements GatewayFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getHeaders().getFirst("token");
if ("imooc".equals(token)){
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE + 2;
}
}
1.2 添加到过滤器工厂
package com.imooc.ecommerce.filter.factory;
import com.imooc.ecommerce.filter.HeaderTokenGatewayFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class HeaderTokenAbstractGatewayFilterFactory extends AbstractGatewayFilterFactory {
@Override
public GatewayFilter apply(Object config) {
return new HeaderTokenGatewayFilter();
}
}
课程截图:323词