nginx技巧--自动API白名单(自动获取微信公众号IP白名单/自动更新)
Administrator
发布于 2022-09-20 / 58 阅读 / 0 评论 / 0 点赞

nginx技巧--自动API白名单(自动获取微信公众号IP白名单/自动更新)

一般企业级WEB接口发布都需要信息安全政策,在Nginx上配置访问来源IP白名单是常用的做法。现在大厂服务都实现高可用&CDN应用,那么又要如何来实现白名单限制?

本文介绍微信公众号对接为例(方法同样适用于企微、钉钉)

流程介绍:
1、获取调用授权参数
2、创建shell脚本,动作:调用官方IP清单=》转为nginx配置格式 *.conf;
3、nginx中server项配置include *.conf;
4、配置shell脚本定时运行;

1.1、首先我们登陆到公众号配置IP白名单(即发起调用的nginx服务器公网IP)和两个参数:appid、 secret (留意把secret参数保存下来,每次获取会刷新),获取方法见下图示例:
公众号参数获取

1.2、关于如何获取微信服务器IP地址,(赶时间可以不看)请见微信官方说明

2.1、创建名为get-uat-crm-wxip.sh 脚本,以下为脚本内容

#!/bin/bash
#通过appid、 secret获取token,赋值于apitoken
apitoken = (curl -s https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="你的appid"&secret="你的secret" 
#用token获取IP清单并赋值给RESULT 
RESULT=(curl -s “https://api.weixin.qq.com/cgi-bin/get_api_domain_ip?access_token=$apitoken”)
#将内容保存到include配置目录
echo $RESULT > get_api_domain_ip.conf

#因微信提供的是json格式,需要替换内容
find -name ‘get_api_domain_ip.conf’ | xargs perl -pi -e ‘s|{“ip_list”:["|allow |g’ #替换头部插入allow
find -name ‘get_api_domain_ip.conf’ | xargs perl -pi -e ‘s|“,”|;\nallow |g’ #换行并插入allow
find -name ‘get_api_domain_ip.conf’ | xargs perl -pi -e ‘s|"]}|;\ndeny all; |g’ #结尾配上deny all

2.2、在服务器上执行
#sh get-uat-crm-wxip.sh

2.3、同步一下效果:
转换之前格式
before-file
转换之后格式
after-file

3.1、配置nginx调用该清单,如下:(调用前配置允许本地IP,本地IP不更新)
nginxconf_20220920222341

4.1、允许get-uat-crm-wxip.sh执行权限
#chmod +x get-uat-crm-wxip.sh

4.2、安装crontab服务

yum install crontabs ------安装

systemctl start crond ------启动

systemctl enable crond ------任务开机自启

4.3、 配置crontab规则

vim /etc/crontab

0 1 * * * /etc/nginx/conf.d/ip_white/get-uat-crm-wxip.sh ----尾行插入,每天凌晨一点执行,自行修改实际执行时间

#crontab /etc/crontab -----保存生效
#$ crontab -l -----查看任务列表

5、结束!


评论