如何在nginx代理中添加API密钥认证?

z9smfwbn  于 2023-10-17  发布在  Nginx
关注(0)|答案(2)|浏览(238)

有没有办法配置https://hub.docker.com/r/jwilder/nginx-proxy/通过硬编码的API密钥添加基本身份验证?
我只能找到NGINX Controller和NGINX Plus的例子,我有点惊讶,开源NGINX的这个非常常见的用例没有太多的例子。
NGINX Plus的例子在这里:https://www.nginx.com/blog/deploying-nginx-plus-as-an-api-gateway-part-1/

zujrkrfu

zujrkrfu1#

这是我在nginx上做的,可能适用于你
1.我在客户端使用“X-APIkey:“头:curl -X POST -H "X-APIkey: my-secret-api-key" https://example.com
1.我在nginx.conf中有一个定义X-APIkeys授权值的Map
1.我使用一个内部位置来使用我需要限制访问的位置中的Map进行密钥验证。

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;
     }
  }
eimct9ow

eimct9ow2#

找到了一个if语句。您可以将其放置在服务器级别或特定位置。

map $http_x_api_key $valid_key {
  default 0;
  "key1" 1;
  "key2" 1;
}

server {
    
    location /authenticated {
      if ($valid_key = 0) {
        return 401; # Unauthorized
      }
      proxy_pass http://service;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
    }

    location / {
        proxy_pass http://service;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

相关问题