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

后端 未结 4 995
孤独总比滥情好
孤独总比滥情好 2020-12-31 02:33

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 03:14

    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...

提交回复
热议问题