萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Nginx + Lua 實現基於 HMAC 簽名的靜態 Token 認證模塊

需求背景

Nginx 反向代理需增加認證層,驗證外部系統登錄狀態。避免每請求子請求驗證帶來的延遲,採用簽名 Token 方案:登錄服務簽發帶過期時間的 HMAC 簽名 Cookie,Nginx Lua 模塊驗證簽名與過期時間,通過則放行。

Nginx 配置

location /protected/ {
    access_by_lua_file /etc/nginx/auth_check.lua;
    proxy_pass https://backend;
}

Lua 驗證腳本

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
-- 驗證通過,繼續代理

Token 簽發服務

使用 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,
    })
}

HTTP Basic Auth 驗證

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 ""
}

安全考量

  • 使用常量時間比較防止時序攻擊。
  • 密鑰需足夠長且安全存儲,生產環境建議從 Vault 等密鑰管理系統讀取。
  • Cookie 設置 HttpOnly、Secure、SameSite 屬性。
  • Token 有效期不宜過長,建議 1-2 小時,支持刷新機制。

總結

Nginx + Lua 實現無狀態 Token 驗證,將認證邏輯前置到網關層,極大降低後端服務壓力。結合外部登錄服務簽發簽名 Token,實現單點登錄與微服務認證解耦。

copyright © 萬盛學電腦網 all rights reserved