文件
一個 專案

forward_auth

一個有意見的指令,會將要求的複製代理至驗證閘道,閘道可以決定是否繼續處理,或需要傳送至登入頁面。

Caddy 的 reverse_proxy 能夠對外部服務執行「預先檢查要求」,但這個指令特別針對驗證使用案例量身打造。這個指令實際上只是使用較長、更常見的設定檔(如下)的便捷方式。

這個指令會對設定的上游執行 GET 要求,並改寫 uri

  • 如果上游回應 2xx 狀態碼,則授予存取權,並將 copy_headers 中的標頭欄位複製至原始要求,然後繼續處理。
  • 否則,如果上游回應任何其他狀態碼,則上游的回應會複製回用戶端。此回應通常會包含重新導向至驗證閘道的登入頁面。

如果此行為並非您想要的,您可以將下方的 擴充形式 作為基礎,並根據您的需求自訂。

支援 reverse_proxy 的所有子指令,並傳遞至底層的 reverse_proxy 處理常式。

語法

forward_auth [<matcher>] [<upstreams...>] {
	uri          <to>
	copy_headers <fields...> {
		<fields...>
	}
}
  • <upstreams...> 是要傳送驗證要求的上游(後端)清單。

  • uri 是要設定在傳送至上游要求的 URI(路徑和查詢)。這通常會是驗證閘道的驗證終端點。

  • copy_headers 是當要求有成功狀態碼時,要從回應複製至原始要求的 HTTP 標頭欄位清單。

    可以使用 > 後接新名稱來重新命名欄位,例如 Before>After

    如果偏好可讀性,可以使用區塊來列出所有欄位,每行一個。

由於此指令是反向代理的意見化包裝器,因此您可以使用 reverse_proxy 的任何子指令來自訂它。

展開形式

forward_auth 指令與下列設定相同。像 Authelia 這樣的驗證閘道器非常適合此預設設定。如果您的閘道器不適合,請隨時借用此設定並依需要自訂,而不是使用 forward_auth 捷徑。

reverse_proxy <upstreams...> {
	# Always GET, so that the incoming
	# request's body is not consumed
	method GET

	# Change the URI to the auth gateway's
	# verification endpoint
	rewrite <to>

	# Forward the original method and URI,
	# since they get rewritten above; this
	# is in addition to other X-Forwarded-*
	# headers already set by reverse_proxy
	header_up X-Forwarded-Method {method}
	header_up X-Forwarded-Uri {uri}

	# On a successful response, copy response headers
	@good status 2xx
	handle_response @good {
		request_header {
			# for example, for each copy_headers field...
			Remote-User {rp.header.Remote-User}
			Remote-Email {rp.header.Remote-Email}
		}
	}
}

範例

Authelia

在透過反向代理提供應用程式服務之前,將驗證委派給 Authelia

# Serve the authentication gateway itself
auth.example.com {
	reverse_proxy authelia:9091
}

# Serve your app
app1.example.com {
	forward_auth authelia:9091 {
		uri /api/verify?rd=https://auth.example.com
		copy_headers Remote-User Remote-Groups Remote-Name Remote-Email
	}

	reverse_proxy app1:8080
}

如需更多資訊,請參閱 Authelia 的文件 以了解如何與 Caddy 整合。

Tailscale

將驗證委派給 Tailscale(目前稱為 nginx-auth,但仍可與 Caddy 搭配使用),並使用 copy_headers 的替代語法來重新命名已複製的標頭(請注意每個標頭中的 >

forward_auth unix//run/tailscale.nginx-auth.sock {
	uri /auth
	header_up Remote-Addr {remote_host}
	header_up Remote-Port {remote_port}
	header_up Original-URI {uri}
	copy_headers {
		Tailscale-User>X-Webauth-User
		Tailscale-Name>X-Webauth-Name
		Tailscale-Login>X-Webauth-Login
		Tailscale-Tailnet>X-Webauth-Tailnet
		Tailscale-Profile-Picture>X-Webauth-Profile-Picture
	}
}