文件
一個 專案

forward_auth

一個有主見的指令,會將請求的副本代理到身份驗證閘道,該閘道可以決定是否應繼續處理,或是否需要發送到登入頁面。

Caddy 的 reverse_proxy 能夠對外部服務執行「預先檢查請求」,但此指令是專門為身份驗證用例量身定制的。此指令實際上只是一種使用更長、更常見配置的便捷方式(如下所示)。

此指令會使用重寫的 uri 向配置的上游發出 GET 請求

  • 如果上游回應 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 {
		# for example, for each copy_headers field...
		request_header Remote-User {rp.header.Remote-User}
		request_header 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/authz/forward-auth
		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
	}
}