Authorization header override in Swagger UI with Nginx

Julian Source

I'm trying to set up a Swagger UI page with my current Nginx configuration, but I'm running into an issue with the HTTP authorization header. The Nginx configuration is as follows:

server {
    listen 80;

    location / {
            proxy_redirect off;
            proxy_buffering off;

            proxy_http_version 1.1;

            proxy_set_header Host $http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location ~ ^/(docs|api-docs) {
            auth_basic "Restricted";
            auth_basic_user_file /home/ubuntu/.htpasswd;


            proxy_http_version 1.1;

I'm attempting to set Basic auth for the resources concerning the documentation, while having the rest of the APIs have their own authorization engine following the Bearer scheme. So for example, to access the URL or I will need to provide a username and password, and to make a successful call to I will need to send the header Authorization: Bearer <token> in the request with a valid access token.

This setup works as expected, except through Swagger UI. The "Try it out" functionality breaks by sending the wrong authorization header. Instead of receiving a header of the form Authorization: Bearer <token>, the server is receiving Authorization: Basic <value> with the credentials used to access the documentation page.

Worth mentioning, the Swagger UI setup for the header looks like this:

window.authorizations.add("key", new ApiKeyAuthorization(
    "Authorization", "Bearer " + key, "header", ":"));

This works when running Swagger UI locally, but breaks when running against the Nginx server. Also, everything works if I remove the second location from the Nginx configuration (loosing Basic auth on /docs and /api-docs).



answered 4 years ago Julian #1

After doing some more research, I think this is due to the browser caching the Basic auth credentials and automatically sending them in the header in subsequent requests.

I decided to follow the advice in this article and implement an auth mechanism for the documentation and the Swagger UI page.

comments powered by Disqus