k8s ingress配置客户端IP

概述

“X-Forwarded-For”(缩写为XFF)是一种HTTP请求头字段,通常由代理服务器或反向代理服务器添加到HTTP请求中,用于跟踪请求经过的代理链和传递客户端的真实IP地址。

例如:

X-Forwarded-For: clientIP, proxy1IP, proxy2IP

配置ingress的configMap

在rancher(2.6)的页面 /storages/configMaps菜单,找到ingress的configMap,设置以下三个属性 (k8s ingress官方说明

apiVersion: v1
data:
  compute-full-forwarded-for: "true"
  forwarded-for-header: X-Forwarded-For
  use-forwarded-headers: "true"

kind: ConfigMap
...

rancher图
在这里插入图片描述

测试链路

postman
k8s ingress
springCloud gateway
springboot app
  • gateway 不需要改造也能转发 “X-Forwarded-For”
  • 通过百度可以查自己的外网IP 百度查IP地址

java 测试

	@PostMapping("/test")
    public Map<String,String> test(HttpServletRequest request){
        Map<String,String> map = new HashMap<>();
        // 取 X-Forwarded-For 的第一个 IP 就是客户端IP
        map.put("ip列表",request.getHeader("X-Forwarded-For"));
        return map;
    }

获取客户端IP工具

public class WebUtils {
    static final String UN_KNOW = "unknown";

    /**
     * 获取客户端IP
     * @return
     */
    public static String getClientIp(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.notNull(attributes, "attributes is null");
        HttpServletRequest request = attributes.getRequest();

        return getClientIp(request);
    }

    /**
     * 获取客户端IP
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");

        if(StringUtils.hasText(ip) && !UN_KNOW.equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值,第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }

        ip = request.getHeader("X-Real-IP");
        if(StringUtils.hasText(ip) && !UN_KNOW.equalsIgnoreCase(ip)){
            return ip;
        }

        return request.getRemoteAddr();
    }
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐