原理:网关生成随机的字符串token并保存在redis中,每次请求服务时,服务端都验证请求头上的token,若请求头上的token与redis中保存的字符串一致则放行,否则拦截!
1.网关生成token(生成后保存在redis,10分钟有效期)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Configuration
public class TokenFilter implements GlobalFilter {
@Autowired
RedisTemplate<String, String> redisTemplate;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String gatewayToken = redisTemplate.opsForValue().get("gatewayToken");
// 将gatewayToken保存至redis
if (gatewayToken == null) {
// 生成gatewayToken
gatewayToken = UUID.randomUUID().toString();
redisTemplate.opsForValue().set("gatewayToken", gatewayToken);
// 十分钟有效期
redisTemplate.expire("gatewayToken", 10, TimeUnit.MINUTES);
}
// 写入请求头
ServerHttpRequest req = exchange.getRequest().mutate()
.header("from", gatewayToken).build();
return chain.filter(exchange.mutate().request(req.mutate().build()).build());
}
}
2.服务端拦截器(用于验证token)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
@Configuration
public class AdminGlobalInterceptor implements HandlerInterceptor {
@Autowired
RedisTemplate<String, String> redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
// 获取当前请求头from信息
String secretKey = request.getHeader("from");
// 获取gatewayToken
String gatewayToken = redisTemplate.opsForValue().get("gatewayToken");
if(secretKey == null || !secretKey.equals(gatewayToken)) {
response.setContentType("application/json;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write("非法访问!");
return false;
}
return true;
}
}