How can I add api key authentication in nginx proxy?

Viewed 4879
1 Answers

Here is what I've done on my nginx, it may apply to you

  1. I use an "X-APIkey:" header on the client side : curl -X POST -H "X-APIkey: my-secret-api-key" https://example.com

  2. I have a map defining X-APIkeys authorized value in the nginx.conf

  3. I use an internal location to do the key verification using the map in the locations I need to restrict the access to.

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

Related