kong插件ip-restriction的X-Forward-For配置
kong配置插件ip-restriction后可以实现对ip黑白名单的限制,对应的lua源码如下。
function IpRestrictionHandler:access(conf)
IpRestrictionHandler.super.access(self)
local block = false
local binary_remote_addr = ngx.var.binary_remote_addr
if not binary_remote_addr then
return responses.send_HTTP_FORBIDDEN("Cannot identify the client IP address, unix domain sockets are not supported.")
end
if conf.blacklist and #conf.blacklist > 0 then
block = iputils.binip_in_cidrs(binary_remote_addr, cidr_cache(conf.blacklist))
end
if conf.whitelist and #conf.whitelist > 0 then
block = not iputils.binip_in_cidrs(binary_remote_addr, cidr_cache(conf.whitelist))
end
if block then
return responses.send_HTTP_FORBIDDEN("Your IP address is not allowed")
end
end
这里先判断黑名单,在判断白名单,也就是说同时将一个ip配置到黑白名单中的,kong会认为他是白名单,不会对其进行限制访问。binary_remote_addr当clinet直接访问kong网关时候,binary_remote_addr是client的ip,如果kong经过nginx代理后(网关高可用,需要负载)binary_remote_addr是代理的ip,那么会有这种情况,后端服务会对一些client的ip进行限制访问时,kong就能起到作用。
解决办法
修改kong配置文件,
- /etc/kong/kong.conf文件,增加trusted_ips = 0.0.0.0/0,::/0 , real_ip_header = X-Forwarded-For
- 需要修改nginx配置文件,增加以下内容
proxy_pass http://test1;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
expires -1;
-
重启nginx和kong,添加client到黑名单验证。
-
参考资料
https://blog.****.net/mx472756841/article/details/81044309