How to send Authorization header with a request in Swagger UI?
Asked Answered
C

4

24

I have a ASP.NET Web Api 2 application. I added Swashbuckle to it (Swagger for .NET). It displays my endpoints no problem, but in order to send a request I need to attach an Authorization header to that request. If I understand correctly in order to do that I need to modify the index.html file (https://github.com/swagger-api/swagger-ui#how-to-use-it) so I git cloned Swashbuckle project in order to modify index.html and add some headers.

Is that the only way to send Authorization header with the request in Swashbuckle?

Crummy answered 20/5, 2015 at 13:9 Comment(8)
github.com/swagger-api/…Rameses
@AlbertoPellizzon - where will I add that code? What file?Crummy
after the swaggerUi initialization try serching where it gets initialized, something like var swaggerUi = new SwaggerUi({});Rameses
I have nothing like that in my code. I have: GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "MyApplication"); }) .EnableSwaggerUi(c => {})); in SwaggerConfig.csCrummy
I think that you are using a wrapper CS of the original JS library that thing should generate JavaScript at the end so find out where the JS isRameses
Right, it looks like I will have to modify index.html that contains some javascript. I will answer the question when I have it fully sorted.Crummy
@Crummy But where is the index.html? I can't find the index.html. It supposed to be generated by Swashbuckle?Kwangju
@Zhou Hao - If I can remember correctly, index.html is available when you run your application and navigate to /swagger. If you want to add a custom index.html you need to grab that HTML, customise it and add it into you application. So index.html is generated by Swashbuckle and "built in" and only visible if you add your own one.Crummy
C
11

In order to send Authorization header with a request using Swagger UI I needed to:

  1. Given the name of my assembly is: My.Assembly and it contains a folder: Swagger, where I placed my custom index.html, I added this line in SwaggerConfig.cs:

     c.CustomAsset("index", thisAssembly, "My.Assembly.Swagger.index.html");
    

Note that index.html loads javascript and css files. I had to change all dots to dashed in the file paths in order for those files to load. I don't know why it had to be done, but it solved the problem of loading the file...

  1. In the index.html file I modified the

    addApiKeyAuthorization()

function to look like that:

function addApiKeyAuthorization() {
        var key = encodeURIComponent($('#input_apiKey')[0].value);
        if (key && key.trim() != "") {
            var value = "auth-scheme api_key=123456,order_id=56789";
            var authKeyHeader = new SwaggerClient.ApiKeyAuthorization("Authorization", value, "header");
            window.swaggerUi.api.clientAuthorizations.add("Authorization", authKeyHeader);
        }
    }

Note I changed "query" to "header".

  1. I also uncommented this code:

    var apiKey = "this field represents header but can be anything as long as its not empty";
    $('#input_apiKey').val(apiKey);
    

which will display text in the second textfield, but it seems it doesn't matter what it contains as long as it is not empty.

That worked for me and enabled me to load custom index.html file. Now I am looking at enabling Swagger UI user to manipulate the value of header parameters...

Crummy answered 26/5, 2015 at 10:55 Comment(1)
It doesn't work for me as well, no errors. Where did you cal addApiKeyAuthorization?Debroahdebs
D
5

I think it's not a good way to send the authorization header by modifying index.html. You can only add some settings to achieve that.
Here is my solution:
1.Add settings in Starup.cs ConfigureServices method

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSwaggerGen(config => {
            config.SwaggerDoc("v1", new OpenApiInfo() { Title = "WebAPI", Version = "v1" });
            config.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey,
                Scheme = "Bearer"
            });
            config.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                    },
                    Array.Empty<string>()
                }
            });
        });
    }

2.Add settings in Startup.cs Configure method

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Document"));
    }

After add settings, then run this project, you can find an Authorization button swagger page, and you can use it to set the authorization header.

Dodge answered 16/12, 2020 at 6:1 Comment(0)
G
4

I added below code in a js file and added it as a embedded resource to my web api project. When you build and run Swagger, api_key textbox will get replaced with Authorization Key Text Box, where you can paste your AuthKey and with every request, swagger will add it to Request header.

(function () {

    $(function () {
        var basicAuthUI =
         '<div class="input"><input placeholder="Authorization Token" id="input_token" name="token" type="text"></div>';
            $(basicAuthUI).insertBefore('#api_selector div.input:last-child');
            $("#input_apiKey").hide();
            $('#input_token').change(addAuthorization);
    });

    function addAuthorization() {
        var token = $('#input_token').val();

        if (token && token.trim() !== "" ) {
            window.swaggerUi.api.clientAuthorizations.add("api_key", new window.SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + token, "header"));
            console.log("authorization added: Bearer = " + token);
        }
    }

})();
Glossematics answered 30/6, 2016 at 14:1 Comment(0)
M
2

for bearer token I've done it that way: I used swashbuckle only for generating the swagger.json file and used Swagger.Net for displaying latest SwaggerUI version (3.xx) and customizing it :

So in my project references, I 'v added (via nuget) :

references

swaggerui

in index.html:

<input id="bearer-code-input" type="text" placeholder="Enter Bearer Token here" style="width: auto" value="yourtoken" />

then in SwaggerUIBundle constructor:

const ui = SwaggerUIBundle({
...,
requestInterceptor: function (req) {
req.headers = {
'Authorization': 'Bearer ' + document.getElementById('bearer-code-
input').value
, 'Accept': 'application/json',
'Content-Type': 'application/json'
};
return req;
},
... })

result display: result

I've also customized a lot of other functions (Json model binder, query string parsing, custom SwaggerGenerator to override the default behavior for ConflictingActionsResolver to be able to handle multiple route paths, but it's not in the scope of this thread)

Marianamariand answered 26/10, 2017 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.