微服务——网关

网关:网络的关口,负责请求的路由、转发、身份校验

前端请求不能直接访问微服务,而是要请求网关:

  • 网关可以做安全控制,也就是登录身份校验,校验通过才放行

  • 通过认证后,网关再根据请求判断应该访问哪个微服务,将请求转发过去

网关路由

配置格式:

复制代码
spring:
  cloud:
    getway:
      routes:
        - id: hmall-gateway
          uri: lb://gateway
          predicates:
            - Path=/api/**
        - id: hmall-item
          uri: lb://item
          predicates:
              - Path=/api/items/**

路由属性:

网关路由对应的Java类型是routeDefinition,其中常见的属性有:

  • id:路由唯一标识
  • uri:路由目标地址
  • predicates:路由断言,判断请求是否符合当前路由
  • filters:路由过滤器,对请求或响应做特俗处理

网关登录校验

在网关内进行JWT校验,在转发之前进行校验

自定义过滤器

网关过滤器有两种

  • GatewayFillter:路由过滤器,作用于任意指定的路由;默认不生效,要配置到路由后生效
  • GlobalFilter:全局过滤器,作用范围是所有路由;声明后自动生效。

两种过滤器的过滤方法签名完全一致

java 复制代码
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain){
        // TODO 模拟登录校验逻辑
        //1.获取请求
        ServerHttpRequest request = exchange.getRequest();
        //2.过滤器业务处理
        HttpHeaders headers = request.getHeaders();//获取请求头
        System.out.println("headers = "+headers);
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //过滤器执行顺序,数值越小,优先级越高
        return 0;
    }
}

实现登录校验

自定义一个过滤器

java 复制代码
package com.hmall.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
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;

import java.util.List;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否需要做登录拦截
        if(isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }
        //3.获取token
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if(headers != null && !headers.isEmpty()){
            token = headers.get(0);
        }
        //4.校验并解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        }catch(UnauthorizedException e){
            //拦截,设置响应状态码
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5.传递用户信息
        System.out.println("userId:=" + userId);
        //6.放行
        return chain.filter(exchange);
    }

    private boolean isExclude(String path){
        for(String excludePath : authProperties.getExcludePaths()){
            if(antPathMatcher.match(excludePath, path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

网关传递用户

1.在网关的登录校验过滤器中,把获取到的用户写入请求头

java 复制代码
        //传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();

2.在common中编写SpringMVC拦截器,获取登录用户

OpenFeign传递用户

相关推荐
沛沛老爹2 小时前
优化 CRM 架构,解锁企业竞争力密码
架构·数字化时代·crm架构·客户关系管理·市场变化·客户满意度
flytalei2 小时前
理解 Kubernetes 的架构与控制平面组件运行机制
平面·架构·kubernetes
zkmall2 小时前
B2C商城架构对比:ZKmall模板商城为何选择 Spring Cloud
spring·spring cloud·架构
shangjg33 小时前
MyBatis 动态 SQL 详解:灵活构建强大查询
java·数据库·架构·mybatis
彭泽布衣4 小时前
阿里云云网络论文:Nezha,计算网络解耦下的vSwitch池化架构
网络·架构·转发·云计算网络·虚拟交换机
向上的车轮6 小时前
Spring Boot微服务架构(二):开发调试常见中文问题
spring boot·微服务·架构
karatttt7 小时前
用go从零构建写一个RPC(3)--异步调用+多路复用实现
网络·后端·rpc·架构·golang
hstar95277 小时前
二十九、面向对象底层逻辑-SpringMVC九大组件之MultipartResolver接口设计
java·spring·设计模式·架构
hstar95277 小时前
三十、面向对象底层逻辑-SpringMVC九大组件之HandlerInterceptor接口设计
java·spring·设计模式·架构
曼汐 .8 小时前
企业网站架构部署与优化-Nginx安全防护与HTTPS部署
安全·架构