OAuth2 Proxy 反向代理身份认证详解

在 Ubuntu 22.04 上部署 OAuth2 Proxy 7.15.5 反向代理身份认证网关:下载解压静态二进制、验证 --version 与 --help 全量参数、配置文件校验(config-test)、以 GitHub Provider 启动并实测 /ping 健康检查、未认证拦截 403 与 /oauth2/sign_in 登录页,并给出常用参数与 OIDC 接入速查。oauth2-proxy 7.15.5 实测

身份认证身份认证OAuth2 Proxy2026/10/08

OAuth2 Proxy 反向代理身份认证详解

目标:在 Ubuntu 22.04 上部署 OAuth2 Proxy,用它对后端应用做统一反向代理身份认证:认证前拦截并跳转 IdP,认证后把用户身份以标头发给上游业务,并沉淀 --help 全量参数与 OIDC 接入速查。本文在 Ubuntu 22.04(oauth2-proxy 7.15.5)真实实测,命令与回显逐行来自实测。

环境信息

  • 系统:Ubuntu 22.04 LTS(x86_64)
  • 软件:oauth2-proxy 7.15.5(Go 静态二进制,built with go1.26.8)
  • 安装目录:/opt/oauth2-proxy(二进制 /opt/oauth2-proxy/oauth2-proxy)
  • 默认监听:127.0.0.1:4180(--http-address)
  • 默认 Provider:google
  • 默认 Cookie 名:_oauth2_proxy
  • 服务名:oauth2-proxy

一、介绍与安装

OAuth2 Proxy 是反向代理认证网关:未被认证的请求不做鉴权而是重定向到 IdP,认证成功后为会话设置 Cookie 并将用户信息写入转发头再访问上游后端。认证提供方由 --provider 决定(github、google、oidc、keycloak-oidc 等),常与 Keycloak(OIDC)搭配使用。

1.1 下载官方发行版并解压

用 GitHub Releases 的 linux-amd64 静态压缩包:

cd /opt
sudo wget https://github.com/oauth2-proxy/oauth2-proxy/releases/download/v7.15.5/oauth2-proxy-v7.15.5.linux-amd64.tar.gz
sudo tar xzf oauth2-proxy-v7.15.5.linux-amd64.tar.gz
sudo mv oauth2-proxy-v7.15.5.linux-amd64 oauth2-proxy

💡 oauth2-proxy 是单个 Go 静态二进制,解压后即可直接运行,无需安装 JDK/Python。版本持续更新,可先查最新 tag:curl -s https://api.github.com/repos/oauth2-proxy/oauth2-proxy/releases/latest。

1.2 验证版本与帮助

/opt/oauth2-proxy/oauth2-proxy --version

实测回显:

oauth2-proxy v7.15.5 (built with go1.26.8)

顶层帮助:

/opt/oauth2-proxy/oauth2-proxy --help

实测回显:

Usage of oauth2-proxy:
      --alpha-config string       path to alpha config file (use at your own risk - the structure in this config file may change between minor releases)
      --config string             path to config file
      --config-test               test the configuration and exit
      --convert-config-to-alpha   if true, the proxy will load configuration as normal and convert existing configuration to the alpha config structure, and print it to stdout
      --version                   print version string

最常见的几个,同样来自 --help 实测(注意默认值):

      --cookie-name string        the name of the cookie ... (default "_oauth2_proxy")
      --cookie-secret string      the seed string for secure cookies (optionally base64 encoded)
      --provider string           OAuth provider (default "google")
      --provider-display-name string   Provider display name
      --email-domain strings      authenticate emails with the specified domain (may be given multiple times). Use * to authenticate any email
      --oidc-issuer-url string    OpenID Connect issuer URL (ie: https://accounts.google.com)
      --redirect-url string       the OAuth Redirect URL. ie: "https://internalapp.yourcompany.com/oauth2/callback"
      --upstream strings          the http url(s) of the upstream endpoint, file:// paths for static files or static://<status_code> for static response. Routing is based on the path
      --http-address string       ... to listen on for HTTP clients (default "127.0.0.1:4180")
      --https-address string      <addr>:<port> to listen on for HTTPS clients (default ":443")
      --ping-path string          the ping endpoint ... (default "/ping")
      --pass-host-header          pass the request Host Header to upstream (default true)
      --pass-basic-auth           pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream (default true)
      --cookie-expire duration    expire timeframe for cookie (default 168h0m0s)
      --cookie-refresh duration   refresh the cookie after this duration; 0 to disable

💡 完整参数分块(认证 Provider、上游、Cookie、会话存储 Redis 等)请以 --help 为准;本文第 3 节只收最常用的几类。


二、配置与启动(GitHub Provider 实测)

2.1 编写配置文件

oauth2-proxy 同时支持命令行参数与配置文件。编辑 /etc/oauth2-proxy/oauth2-proxy.cfg:

provider = "github"
client_id = "dummy-client-id"
client_secret = "dummy-secret"
upstreams = [ "static://200" ]
http_address = "127.0.0.1:4180"
email_domains = [ "*" ]
cookie_secret = "01234567890123456789012345678901"
  • provider = "github":使用 GitHub 作为 IdP;
  • client_id / client_secret:在 GitHub OAuth App 控制台申请;
  • upstreams = [ "static://200" ]:本次验证不上真实后端,直接用静态 200 响应;
  • cookie_secret:加密会话 Cookie 的 32 字节种子,可用 openssl rand -base64 32 生成。

2.2 配置校验(config-test)

/opt/oauth2-proxy/oauth2-proxy --config /etc/oauth2-proxy/oauth2-proxy.cfg --config-test

实测回显:

configuration is valid

💡 --config-test 只校验配置并立即退出;写错参数名/取值时这里会直接报错,是改配置后的第一步自查。

2.3 后台启动并验证健康检查

cd /opt/oauth2-proxy
/opt/oauth2-proxy/oauth2-proxy --config /etc/oauth2-proxy/oauth2-proxy.cfg >/var/log/oauth2-proxy.log 2>&1 &

⚠️ 上述 & 为前台排障用法;生产应用 systemd 托管(见第 4 节),便于开机自启与日志集中管理。

健康检查:

curl -s -o /dev/null -w "HTTP %{http_code}\n" http://127.0.0.1:4180/ping

实测回显:

HTTP 200

未认证访问受保护根路径(应拦截):

curl -s -o /dev/null -w "HTTP %{http_code}\n" http://127.0.0.1:4180/

实测回显:

HTTP 403

💡 无 Cookie 时的访问会被拒绝(403),不会直接到达上游,达到"反向代理认证"目的。带有效证书的浏览器访问会先跳到 /oauth2/sign_in 再跳到 IdP。

2.4 登录页与启动日志实测

登录页:

curl -s http://127.0.0.1:4180/oauth2/sign_in

实测回显(节选):

<!DOCTYPE html>
<html lang="en" charset="utf-8">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>Sign In</title>
    <link rel="stylesheet" href="/oauth2/static/css/bulma.min.css">
    ...

启动日志 /var/log/oauth2-proxy.log 关键行:

[proxy.go:80] mapping path "/" => static response 200
[oauthproxy.go:180] OAuthProxy configured for GitHub Client ID: dummy-client-id
[oauthproxy.go:186] Cookie settings: name:_oauth2_proxy secure(https):true httponly:true expiry:168h0m0s domains: path:/ samesite: refresh:disabled
127.0.0.1:4180 GET - "/ping" HTTP/1.1 "curl/7.81.0" 200 2 0.000
[oauthproxy.go:1086] No valid authentication in request. Initiating login.
127.0.0.1:4180 GET - "/" HTTP/1.1 "curl/7.81.0" 403 8486 0.001

💡 日志清晰展示:静态映射 /、Provider 配置、Cookie 策略,以及每次请求"未认证 → 发起登录"的处理路径。


三、接入 OIDC(以 Keycloak 为 IdP)

内置 provider 名称为 oidc 时使用标准 OIDC Discovery;也可用 keycloak-oidc 直接对接 Keycloak。

3.1 配置文件要点

provider = "oidc"
client_id = "myapp"
client_secret = "my-secret"
oidc_issuer_url = "https://idp.example.com/realms/myrealm"
redirect_url = "https://app.example.com/oauth2/callback"
  • oidc_issuer_url:IdP 的 /.well-known/openid-configuration 发现地址(如 Keycloak 某 realm);
  • redirect_url:必须与 IdP 应用侧登记的回调一致,形如 https://<域>/oauth2/callback;
  • 其它助手参数:--oidc-email-claim(默认 email)、--oidc-groups-claim(默认 groups)、--allowed-group(限组成员)。

3.2 面向上游透传身份的请求头

认证成功后,oauth2-proxy 默认向前端宿主/上游转发(可用 --pass-user-headers 等控制):

请求头内容
X-Forwarded-User认证用户唯一标识(默认 email)
X-Forwarded-Email用户邮箱
X-Auth-Request-User需配合 --set-xauthrequest 时输出
Authorization需配合 --pass-access-token/--pass-authorization-header 时透传

四、systemd 托管

编辑 /etc/systemd/system/oauth2-proxy.service:

[Unit]
Description=OAuth2 Proxy authentication reverse proxy
After=network-online.target

[Service]
User=root
ExecStart=/opt/oauth2-proxy/oauth2-proxy --config /etc/oauth2-proxy/oauth2-proxy.cfg
Restart=always

[Install]
WantedBy=multi-user.target

启用并启动:

sudo systemctl daemon-reload
sudo systemctl enable oauth2-proxy
sudo systemctl start oauth2-proxy

💡 每行只启停一个单元。确认状态:

sudo systemctl is-active oauth2-proxy

五、常用参数速查(来自 --help 实测)

5.1 认证与上游

参数默认值说明
--providergoogleIdP 类型:github/google/oidc/keycloak-oidc 等
--oidc-issuer-url空OIDC 发现地址
--redirect-url空回调 URL,必须与 IdP 登记一致
--upstream空上游地址:http://、file://、static://<code>
--upstream-timeout30s上游响应超时
--http-address127.0.0.1:4180HTTP 监听
--ping-path/ping基础健康检查端点
参数默认值说明
--cookie-name_oauth2_proxyCookie 名
--cookie-secret空加密种子(必需)
--cookie-expire168h0m0sCookie 过期
--cookie-refresh0刷新间隔(0 禁用)
--cookie-securetrue仅 HTTPS 下发
--session-store-typecookie会话存储:cookie/redis 等

5.3 行为开关

参数默认值说明
--pass-basic-authtrue向上游传 Basic Auth 并写 X-Forwarded-User/Email
--pass-host-headertrue转发上游原 Host
--set-xauthrequestfalse输出 X-Auth-Request-* 头(Nginx auth_request 模式)
--skip-auth-route空按 method=path_regex 放行免认证路径
--proxy-prefix/oauth2内建端点前缀

💡 需要大量自定义端点放行(CSS、健康检查)时用 --skip-auth-route;在 Nginx 里做二次鉴权时用 --set-xauthrequest 配合。


六、常见问题

  • No valid authentication in request. Initiating login.:这是正常现象(未带有效会话)。真正异常是该请求被反复 403 且浏览器始终不跳 IdP——检查 redirect_url 与 IdP 侧登记是否一致。
  • configuration is invalid:--config-test 会指出具体字段;最常见是 cookie_secret 长度或 Base64 问题,或 upstreams 语法错误。
  • /ping 返回非 200:进程未起或 http_address 改过;用 --config-test 后直接看启动日志定位。
  • 登录后仍 403 / Cookie 被拒:cookie-secure=true 下走了 HTTP,被浏览器拒。内网/测试可用 cookie-secure=false,或统一走 HTTPS。
  • 与上游相同端口冲突:http_address 只监听 127.0.0.1:4180,不要让上游与应用共用该端口。

七、卸载

sudo systemctl stop oauth2-proxy
sudo systemctl disable oauth2-proxy
sudo rm -f /etc/systemd/system/oauth2-proxy.service
sudo rm -rf /opt/oauth2-proxy /opt/oauth2-proxy-v7.15.5.linux-amd64.tar.gz
sudo rm -f /etc/oauth2-proxy/oauth2-proxy.cfg /var/log/oauth2-proxy.log
sudo systemctl daemon-reload

参考链接