REST api auto-athenticate with nginx adding bearer token

Hi, My Wago device (Codesys 2.3) can make http requests but I didn’t find a way to add custom headers to them so figured out Nginx will add them for me. I configured nginx with following file:

server {
        listen  80;
        location /api {
                proxy_pass  http://127.0.0.1:8123/api;
                proxy_set_header Content-Type application/json;
                proxy_set_header Authorization "Bearer will.not.show.my.actual.token";
        }
}

But am getting

root@nuc:~/nginx# curl -X GET http://localhost:8456/api/states/sensor.energia_dzisiaj
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.23.3</center>
</body>
</html>

and in nginx log:

2022/12/19 20:27:16 [error] 37#37: *8 connect() failed (111: Connection refused) while connecting to upstream, client: 172.30.32.1, server: , request: "GET /api/states/sensor.energia_dzisiaj HTTP/1.1", upstream: "http://127.0.0.1:8123/api/states/sensor.energia_dzisiaj", host: "localhost:8456"
172.30.32.1 - - [19/Dec/2022:20:27:16 +0000] "GET /api/states/sensor.energia_dzisiaj HTTP/1.1" 502 157 "-" "curl/7.74.0" "-"

So to me it seems like nginx isn’t forwarding the authorization header correctly. I spent whole evening figuring out the reason but ran out of ideas. Can anyone take a look? I bet the issue with my settings is obvious, but I’m just to tired to see it.

1 Like

Figured it out myself. I decided to use nginx in docker container so

proxy_pass  http://127.0.0.1:8123/api;

actually tries to reach endpoint in that very container. To make it work properly two thing has to be configured:

  1. add --add-host host.docker.internal:host-gateway to docker run command
  2. replace 172.0.0.1 address with host.docker.internal so configuration file looks like
server {
        listen  80;
        location /api {
                proxy_pass  http://host.docker.internal:8123/api;
                proxy_set_header Content-Type application/json;
                proxy_set_header Authorization "Bearer will.not.show.my.actual.token";
        }
}

And now it works:

root@nuc:~# curl -X GET http://localhost:8456/api/states/sensor.energia_dzisiaj
{"entity_id":"sensor.energia_dzisiaj","state":"3.75","attributes":{"unit_of_measurement":"kWh","friendly_name":"Energia dzisiaj"},"last_changed":"2022-12-19T15:01:04.444216+00:00","last_updated":"2022-12-19T15:01:04.444216+00:00","context":{"id":"01GMNEE49WNNA7CSZZCBZ3AJWX","parent_id":null,"user_id":null}}root@nuc:~#
1 Like