Nginx 訪問權限管理

前段時間,團隊開放了組件庫演示環境,由於存在一些小夥伴在外地辦公(只能外網或者 vpn 到內網)。所以,爲了安全考慮,設想是否可以通過 Nginx 做一些訪問限制呢?當然,答案是肯定的。

訴求整理:

  • 內網:爲了便利性,隨意訪問,不設限制;
  • 外網:通過指定的用戶名和密碼訪問(當然,要求祕鑰的保密性)。

增加認證

這個很簡單,使用 Nginx 的 ngx_http_auth_basic_module 模塊,即可完成。

ngx_http_auth_basic_module 模塊允許通過使用“HTTP基本身份驗證”協議驗證用戶名和密碼來限制對資源的訪問。

location / {
    auth_basic "請輸入密碼或聯繫IDSS-FE相關成員";			 # 提示
    auth_basic_user_file /usr/local/nginx/.passwd; # 密鑰文件
}

上述 auth_basicauth_basic_user_file 作用域均爲 http, server, location, limit_excep

對於密碼形式,其支持(具體可以查看參考鏈接 Nginx 相關模塊信息):

  • crypt() 函數加密; 可以使用 Apache HTTP Server發行版中的 “htpasswd” 實用程序或 “openssl passwd” 命令生成;
  • 使用基於 MD5 的密碼算法(apr1)的 Apache 變體進行散列;
  • RFC 2307 中描述的 “{scheme} data” 語法(1.0.3+)指定;

生成密碼

這裏使用 Apache 的 htpasswd 工具生成。

htpasswd - Manage user files for basic authentication

# [可選]安裝 httpd-tools
$ yum install -y httpd-tools
# 生成密鑰文件
$ htpasswd -c /usr/local/nginx/.passwd idss-fe
# 按提示輸入密碼、確認密碼,即完成配置
  • - c 創建 passwd 文件。如果 passwdfile 已存在,則會重寫並截斷。此選項不能與 -n 選項組合使用。(具體可查看參考鏈接 Apach 相關文檔)
  • idss-fe 爲用戶名,會添加到 .passwd 文件中

生成的內容,格式如下:

idss-fe:$apr111$d/Rw..nPddMiS...FSg0tho0

上述,整體處理完成,不要忘記 $ nginx -s reload

訪問限制

只針對外網做限制。其中,這裏實現的思路,是逆向的。外網的 IP,沒辦法窮舉;但是我們部署的服務器,和我們自身的內網環境是屬於同一個網段,我們放行該網段,同時禁止其他所有訪問,也就達到了上述目的。

這裏使用 Nginx 的核心模塊 Module ngx_http_core_module 中的 satisfyngx_http_access_module 模塊結合實現。

ngx_http_access_module模塊允許限制對某些客戶端地址的訪問

location / {
    satisfy any;	# 下述 access 和 auth_basic 任意通過即可

    allow 192.168.1.0/32; # 只需求該網段,其他全部禁止
    deny  all;

    auth_basic "請輸入密碼或聯繫IDSS-FE相關成員";
    auth_basic_user_file /usr/local/nginx/.passwd;
}
  • satisfy all 全部或 satisfy any 下述任意一個 ngx_http_access_modulengx_http_auth_basic_modulengx_http_auth_request_modulengx_http_auth_jwt_module 模塊允許訪問,則允許訪問。 作用域 http, server, location
  • allow 同時支持 IPv4/IPv6。allow 192.168.1.0/32; allow 2001:0db8::/32; 作用域 http, server, location, limit_except。(具體可查看參考鏈接 access module 相關文檔)

附:完整配置

ocation / {
  satisfy any;
  
  allow 192.168.101.0/32;
  deny all;
  
  auth_basic "請輸入密碼或聯繫IDSS-FE相關成員";	
  auth_basic_user_file /usr/local/nginx/.passwd;
    
  root   /idss/demo-collection/dist;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html;
}

參考地址

我的博客即將同步至騰訊雲+社區,邀請大家一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=2704r1t8r6680

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