如何在 nginx 代理中添加 api 密钥身份验证?

FCR*_*FCR 3 authentication nginx api-key docker

有没有办法配置https://hub.docker.com/r/jwilder/nginx-proxy/以通过硬编码 api 密钥添加基本身份验证?

我只能找到 NGINX 控制器和 NGINX Plus 的示例,令我有点惊讶的是,对于开源 NGINX 的这种非常常见的用例,没有太多示例。

NGINX Plus 的示例在这里:https ://www.nginx.com/blog/deploying-nginx-plus-as-an-api-gateway-part-1/

小智 7

这是我在 nginx 上所做的,它可能适用于你

  1. 我在客户端使用“X-APIkey:”标头:curl -X POST -H "X-APIkey: my-secret-api-key" https://example.com

  2. 我有一个在 nginx.conf 中定义 X-APIkeys 授权值的映射

  3. 我使用内部位置来使用我需要限制访问的位置中的地图进行密钥验证。

map $http_x_apikey $api_realm {
    default "";
    "my-secret-api-key" "ipfs_id";
    "this-one-too-is-kinda-secret" "ipfs_cmd";
    "however-this-one-is-well-known" "ipfs_api";
    "password" "ipfs_admin";
}
Run Code Online (Sandbox Code Playgroud)
 # API keys verification
  location = /authorize_apikey {
     internal;
     if ($api_realm = "") {
        return 403; # Forbidden
     }
     if ($http_x_apikey = "") {
        return 401; # Unauthorized
     }
     return 204; # OK
  }
Run Code Online (Sandbox Code Playgroud)
location /api/v0/cmd {
     proxy_pass  http://ipfs-api;
     if ($request_method = 'OPTIONS') {
        add_header Access-Control-Allow-Headers "X-APIkey, Authorization";
     }
     satisfy any;
     auth_request /authorize_apikey;
     limit_except OPTIONS {
        auth_basic "Restricted API ($api_realm)";
        auth_basic_user_file /etc/nginx/htpasswd-api-add;
     }
  }

Run Code Online (Sandbox Code Playgroud)