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/
Here is what I've done on my nginx, it may apply to you
I use an "X-APIkey:" header on the client side : curl -X POST -H "X-APIkey: my-secret-api-key" https://example.com
I have a map defining X-APIkeys authorized value in the nginx.conf
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;
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With