NGINX基於子請求結果的身份驗證

介紹

NGINX和NGINX Plus可以通過外部服務器或服務驗證每個對您網站的請求。爲了執行身份驗證,NGINX向驗證子請求的外部服務器發出HTTP子請求。如果子請求返回2xx響應代碼,則允許訪問;如果子請求返回401或403,則拒絕訪問。此類身份驗證允許實現各種身份驗證方案,例如多因素身份驗證,或者允許實現LDAP或OAuth身份驗證。

先決條件

  • NGINX Plus或NGINX開源版
  • 外部認證服務器或服務

配置NGINX和NGINX Plus

  1. 確保使用with-http_auth_request_module配置選項編譯了NGINX開源。運行此命令並驗證輸出是否包括 --with-http_auth_request_module:
$ nginx -V 2>&1 | grep -- 'http_auth_request_module'
  1. 在需要請求身份驗證的位置,指定auth_request指令,在該指令中指定將授權子請求轉發到的內部位置:
location /private/ {
    auth_request /auth;
    #...
}

在這裏,對於每個到 /private 的請求,都會向內部 /auth 位置發出一個子請求。

  1. 指定一個內部位置和此位置內的proxy_pass指令,該指令將把身份驗證子請求代理到身份驗證服務器或服務:
location = /auth {
    internal;
    proxy_pass http://auth-server;
    #...
}
  1. 由於身份驗證子請求將丟棄請求體,因此需要將proxy-pass-request-body指令設置爲off,並將Content-Length頭設置爲空字符串:
location = /auth {
    internal;
    proxy_pass              http://auth-server;
    proxy_pass_request_body off;
    proxy_set_header        Content-Length "";
    #...
}
  1. 使用帶有proxy_set_header指令的參數傳遞完整的原始請求URI:
location = /auth {
    internal;
    proxy_pass              http://auth-server;
    proxy_pass_request_body off;
    proxy_set_header        Content-Length "";
    proxy_set_header        X-Original-URI $request_uri;
}
  1. 作爲選擇,您可以使用auth_request_set指令根據子請求的結果設置變量值:
location /private/ {
    auth_request        /auth;
    auth_request_set $auth_status $upstream_status;
}

完整的例子

本示例將前面的步驟總結爲一個配置:

http {
    #...
    server {
    #...
        location /private/ {
            auth_request     /auth;
            auth_request_set $auth_status $upstream_status;
        }

        location = /auth {
            internal;
            proxy_pass              http://auth-server;
            proxy_pass_request_body off;
            proxy_set_header        Content-Length "";
            proxy_set_header        X-Original-URI $request_uri;
        }
    }
}

參考文檔

https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-subrequest-authentication/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章