Enable bearer token in Swashbuckle (Swagger document)

Update

The issue detailed below is now resolved in Swashbuckle v5.5.0.

Issue

Just ran into the exact same issue. I think the root cause is this line in Swashbuckle’s source code:

var key = encodeURIComponent($('#input_apiKey')[0].value);

This is where the value from the HTML input field goes through URL encoding turning the space into %20. I’m planning to open an issue in the Swashbuckle repo on GitHub.

Workaround

Until that issue is resolved, here is a workaround based on replacing the above line using a Javascript file injected into the Swagger UI:

  1. In the project where you have Swashbuckle installed, create a new folder and call it “Swagger”.

  2. In the new folder create a new Javascript file called “SwaggerUiCustomization.js” and put this script in it:

    (function () {
        function addApiKeyAuthorization() {
            var key = $('#input_apiKey')[0].value;
            if (key && key.trim() != "") {
                var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization(swashbuckleConfig.apiKeyName, key, swashbuckleConfig.apiKeyIn);
                window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
                log("added key " + key);
            }
        }
        $('#input_apiKey').change(addApiKeyAuthorization);
    })();
    
  3. In the Solution Explorer, choose the file and hit Alt+Enter to edit its Properties. In the Properties window change the file’s Build Action to Embedded Resource.

  4. In your SwaggerConfig.cs file add the following line inside the EnableSwaggerUi() code block:
    c.InjectJavaScript(thisAssembly,
    "<Project_Default_Namespace>.Swagger.SwaggerUiCustomization.js");

    Be sure, of course, to replace <Project_Default_Namespace> with your project’s default namespace.

  5. Run your project and enter “Bearer ” into the text box. When you invoke a controller action, you should get this exact same value – with a whitespace instead of %20% – on the server side.

Leave a Comment