Nginx 反向代理需增加認證層,驗證外部系統登錄狀態。避免每請求子請求驗證帶來的延遲,採用簽名 Token 方案:登錄服務簽發帶過期時間的 HMAC 簽名 Cookie,Nginx Lua 模塊驗證簽名與過期時間,通過則放行。
location /protected/ {
access_by_lua_file /etc/nginx/auth_check.lua;
proxy_pass https://backend;
}
local cookie = ngx.var.cookie_MyToken
if not cookie or not cookie:find(":") then
return ngx.exec("/auth/") -- 重定向登錄
end
local divider = cookie:find(":")
local timestamp = cookie:sub(1, divider - 1)
local hmac = cookie:sub(divider + 1)
-- 常量時間比較防時序攻擊
local function const_eq(a, b)
if #a ~= #b then return false end
local diff = 0
for i = 1, #a do
diff = bit.bor(diff, bit.bxor(string.byte(a, i), string.byte(b, i)))
end
return diff == 0
end
local secret = "some very secret string"
local expected = ngx.hmac_sha1(secret, timestamp)
if not const_eq(expected, hmac) or tonumber(timestamp) < ngx.time() then
return ngx.exec("/auth/")
end
-- 驗證通過,繼續代理
使用 Go 實現 HTTP Basic Auth 登錄驗證,簽發 HMAC-SHA1 簽名 Cookie。
func getToken() string {
exp := time.Now().Add(1 * time.Hour).Unix()
mac := hmac.New(sha1.New, []byte("some very secret string"))
mac.Write([]byte(fmt.Sprintf("%d", exp)))
sig := fmt.Sprintf("%x", mac.Sum(nil))
return fmt.Sprintf("%d:%s", exp, sig)
}
func setTokenCookie(w http.ResponseWriter, token string) {
http.SetCookie(w, &http.Cookie{
Name: "MyToken", Value: token, Path: "/",
Domain: ".example.com", Expires: time.Now().Add(1 * time.Hour),
HttpOnly: true, Secure: true,
})
}
func checkAuth(r *http.Request) string {
auth := r.Header.Get("Authorization")
if auth == "" { return "" }
parts := strings.SplitN(auth, " ", 2)
if parts[0] != "Basic" { return "" }
decoded, _ := base64.StdEncoding.DecodeString(parts[1])
userPass := strings.SplitN(string(decoded), ":", 2)
if len(userPass) != 2 { return "" }
if userPass[0] == "username" && userPass[1] == "password" {
return userPass[0]
}
return ""
}
HttpOnly、Secure、SameSite 屬性。Nginx + Lua 實現無狀態 Token 驗證,將認證邏輯前置到網關層,極大降低後端服務壓力。結合外部登錄服務簽發簽名 Token,實現單點登錄與微服務認證解耦。