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;

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章