EKS ALB Ingress Controller配置:Header校验不通过返回错误码
解决方案:基于请求头的ALB访问控制与路由规则
要实现仅携带指定请求头的合法请求可访问ALB,其余请求返回错误码的需求,核心是利用ALB的规则匹配优先级:先配置匹配合法请求的规则,再配置默认规则捕获所有不符合的请求并返回错误。以下是具体配置步骤和示例:
1. 定义自定义动作与匹配条件
在Ingress注解中定义两个核心动作,以及匹配合法请求的条件:
- 合法请求的重定向动作:当请求头
X的值为123时,重定向到指定地址 - 非法请求的错误响应动作:捕获所有未匹配到合法规则的请求,返回错误码(如403)
annotations: # 合法请求的重定向动作配置 alb.ingress.kubernetes.io/actions.allow-redirect: > {"type":"redirect","redirectConfig":{"protocol":"HTTPS","port":"443","host":"your-target-domain.com","path":"/target-path","statusCode":"302"}} # 非法请求的错误响应动作配置 alb.ingress.kubernetes.io/actions.deny-access: > {"type":"fixed-response","fixedResponseConfig":{"contentType":"text/plain","statusCode":"403","messageBody":"Access Denied: Invalid or missing header"}} # 匹配合法请求头的条件 alb.ingress.kubernetes.io/conditions.allow-redirect: > [{"field":"http-header","httpHeaderConfig":{"httpHeaderName":"X","values":["123"]}}]
2. 配置Ingress规则顺序
ALB会按照rules的定义顺序依次匹配请求,因此必须将合法请求规则放在最前面,最后配置匹配所有路径的默认规则来拦截非法请求:
spec: rules: - host: your-domain.com http: paths: # 第一规则:匹配携带合法请求头的请求,执行重定向 - path: /* pathType: Prefix backend: service: name: allow-redirect port: name: use-annotation # 第二规则:捕获所有未匹配的请求,返回403错误 - path: /* pathType: Prefix backend: service: name: deny-access port: name: use-annotation
关键细节说明
- 规则优先级:ALB匹配到第一个符合条件的规则后会停止后续匹配,因此合法规则必须优先于默认规则
- 重定向参数:可根据需求调整
redirectConfig中的host、path、statusCode(301为永久重定向,302为临时重定向) - 错误码选择:根据场景可选401(未授权)或403(禁止访问),同时自定义
messageBody提示内容 - CloudFront配合:需确保CloudFront转发请求时自动添加
X:123请求头,且禁止客户端直接修改该头(可通过CloudFront缓存策略或函数实现)
完整Ingress配置示例
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: secure-alb-ingress annotations: alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip # 自定义动作与条件 alb.ingress.kubernetes.io/actions.allow-redirect: > {"type":"redirect","redirectConfig":{"protocol":"HTTPS","port":"443","host":"your-target-domain.com","path":"/welcome","statusCode":"302"}} alb.ingress.kubernetes.io/actions.deny-access: > {"type":"fixed-response","fixedResponseConfig":{"contentType":"text/plain","statusCode":"403","messageBody":"Access Denied: Only requests from CloudFront are allowed"}} alb.ingress.kubernetes.io/conditions.allow-redirect: > [{"field":"http-header","httpHeaderConfig":{"httpHeaderName":"X","values":["123"]}}] spec: ingressClassName: alb rules: - host: your-domain.com http: paths: - path: /* pathType: Prefix backend: service: name: allow-redirect port: name: use-annotation - path: /* pathType: Prefix backend: service: name: deny-access port: name: use-annotation
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

