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

时间:2020-05-20 11:47:24

标签: docker authentication nginx api-key

是否可以配置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/

1 个答案:

答案 0 :(得分:0)

这是我在我的 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";
}
 # API keys verification
  location = /authorize_apikey {
     internal;
     if ($api_realm = "") {
        return 403; # Forbidden
     }
     if ($http_x_apikey = "") {
        return 401; # Unauthorized
     }
     return 204; # OK
  }
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;
     }
  }