Doug Sanders
Doug Sanders

Reputation: 21

Issue a custom token from NGINX

I am new to NGINX. I'm wondering if it is possible to, with a single request to NGINX, make two proxy calls that affect the outcome of the response.

Specifically, I'm wanting to add a token to the response of an NGINX request where the token is given as a response header from a separate service.

Theoretically, it might look something like...

location / {

# Call to token service and set the response to a variable, maybe?

# proxy_pass Make the actual call

# Add token from step one to response headers

}

I don't know if this is supported by NGINX, if I need to delve into a custom module, or if this is just a bad idea.

Thanks.

Upvotes: 1

Views: 846

Answers (1)

Doug Sanders
Doug Sanders

Reputation: 21

Got it!

    location / {
      if ($http_x_entry_id = "") {
        return 302 /entry;
      }

      auth_request /token/test-token;
      auth_request_set $token $upstream_http_x_test_token;

      set $test_ui test-ui;
      proxy_pass http://$test_ui;

      add_header X-My-Token "$token";
    }

    location /token/test-token {
      internal;
      set $token_api token-api;

      error_page 500 =401 /error/401;
      error_page 400 =401 /error/401;

      proxy_method POST;
      proxy_pass_request_body off;
      proxy_set_header Content-Length "";
      proxy_set_header X-Original-URI $request_uri;
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;

      rewrite /token/(.*) "/$1/$http_x_entry_id" break;
      proxy_pass http://$token_api:8080;
    }

Upvotes: 1

Related Questions