且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何保证微服务接口的安全? | 带你读《Spring Cloud Alibaba(2019)》之十一

更新时间:2021-09-05 17:25:26

上一篇:Gateway怎样实现服务转发? | 带你读《Spring Cloud Alibaba(2019)》之十
下一篇:如何动态请求参数网关? | 带你读《Spring Cloud Alibaba(2019)》之十二

本文来自于《精通Spring Cloud Alibaba》课程的整理,讲师为余胜军,点击查看视频内容
本文系志愿者整理,供配合学习中心课程使用,不做商业用途。

如何保证微服务接口的安全

接口分为内网和外网接口

外网接口 基于OATUH2.0构建开放平台 比如appid、appsocet获取accesstoken调用接口。
内网接口:都是当前内网中实现通讯,相对于来说比较安全的。

1、需要保证接口幂等性问题(基于Token)
2、接口采用安全加密传输 https协议
3、防止数据被篡改 md5验证签名
4、使用微服务网关实现Api授权认证等、黑名单白名单。
5、对我们的接口实现服务的保护 隔离、熔断、降级等等。
最后使用apiswagger管理我们的微服务接口。

GateWay如何保证高可用和集群

使用Nginx或者lvs虚拟vip访问增加系统的高可用

如何保证微服务接口的安全? | 带你读《Spring Cloud Alibaba(2019)》之十一
环境配置:
网关1 127.0.0.1:81
网关2 127.0.0.1:82
Nginx服务器 127.0.0.1:80

网关过滤器相关配置

private String serverPort;

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    //如何获取参数呢?
    String token = exchange.getRequest().getQueryParams().getFirst("token");
    if (StringUtils.isEmpty(token)) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        String msg = "token not is null ";
        DataBuffer buffer = response.bufferFactory().wrap(msg.getBytes());
        return response.writeWith(Mono.just(buffer));
    }
    // 在请求头中存放serverPort serverPort
    ServerHttpRequest request = exchange.getRequest().mutate().header("serverPort", serverPort).build();
    return chain.filter(exchange.mutate().request(request).build());
}

Nginx相关配置

upstream mayiktgwadds {
  server 127.0.0.1:81;
  server 127.0.0.1:82;
}

server {
  listen 80;
  server_name  gw.mayikt.com;
  location / {
    proxy_pass http://mayiktgwadds/;
  }
}

会员服务获取端口号:

如何保证微服务接口的安全? | 带你读《Spring Cloud Alibaba(2019)》之十一

执行结果:
如何保证微服务接口的安全? | 带你读《Spring Cloud Alibaba(2019)》之十一

如何保证微服务接口的安全? | 带你读《Spring Cloud Alibaba(2019)》之十一