Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add api key authentication in nginx proxy?

Is there a way to configure https://hub.docker.com/r/jwilder/nginx-proxy/ to add basic authentication by hardcoded api keys?

I can only find examples for NGINX Controller and NGINX Plus and I am kind of surprised that there are not many examples out there for this very common use case with open source NGINX.

The example for NGINX Plus is here: https://www.nginx.com/blog/deploying-nginx-plus-as-an-api-gateway-part-1/

like image 644
FCR Avatar asked Oct 27 '25 08:10

FCR


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

like image 186
drit Avatar answered Oct 28 '25 22:10

drit


Found an if statement works well. You can put it at the server level or on a specific location.

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;
    }
}
like image 27
Dustin Butler Avatar answered Oct 29 '25 00:10

Dustin Butler