Luca Marzi
Luca Marzi

Reputation: 806

nginx proxy request to service with header value from an authentication http request

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

Upvotes: 3

Views: 5125

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15478

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

Upvotes: 5

Related Questions