3

This is what I'd like to achieve:

enter image description here

I want to use nginx as a classic reverse proxy to expose server's resources. Before calling the server, nginx should ask a token to the token issuer (an internal service) and inject this token into the authentication header of the call towards the server.

Is it possibile to achieve this with nginx? I looked around inside the nginx documentation and I know I can use proxy_set_header to modify the headers being proxied to the server.

Update

I was able to make the solution below work; here is a POC on github

4
  • Check the ngx_http_auth_request module. Commented Nov 16, 2020 at 11:31
  • I don't find an example in which I take the response from the subrequest and "inject" it into the proxied request. Commented Nov 16, 2020 at 15:30
  • How does the token issuer returns the token? In the response body or via some HTTP header? In second case you can use the auth_request_set directive. Commented Nov 16, 2020 at 15:36
  • That's up to me. I'd prefer to keep it in the body, but I can still live with the fact it is returned as part of the response header. Commented Nov 16, 2020 at 15:57

1 Answer 1

5

If you can make your token issuer to return the token via some HTTP header, for example the X-JWT-Token, here is an example that should work for you:

location /auth {
    internal;
    proxy_pass http://token-issuer;
    proxy_pass_request_body off;
    proxy_set_header Content-Length 0;
    # You can pass an additional data for the token issuer, for example
    # proxy_set_header X-Original-URI $request_uri;
}
location / {
    auth_request /auth;
    auth_request_set $token $upstream_http_x_jwt_token;
    proxy_set_header Authorization "Bearer $token";
    proxy_pass http://upstream;
}
Sign up to request clarification or add additional context in comments.

3 Comments

It works; what if I'd like the token to be returned inside the token-issuer body?
@LucaMarzi I don't know if it is possible with the vanilla nginx at all (if you'd manage to find such solution, please share it with the others). It can be possible with the third party modules that support subrequests (using njs via ngx_http_js_module (example) or via lua-nginx-module using the ngx.location.capture function).
I created this POC on github to test the solution above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.