Basic Authentication – Swagger UI in Asp.Net Web API

In one of my previous article Swagger UI on Asp.Net Web API for Help Pages, we discussed how to implement Swagger UI for an Asp.Net Web API. By default, Swagger UI implemented with api_key, as shown below.

But basic authentication implements through username password. For more information on basic authentication in Asp.Net Web API, check Basic Authentication in Asp.Net Web API (Rest API) article.

To implement basic authentication on UI, we have to make some code changes for our API. First, we need to change the Swagger UI through custom jQuery function. Add new folder to API solution and name it as Custom. Add new javascript file to that Custom folder with the name as basic-authentication.js and add below code.

(function () {
    $(function () {
        var basicAuthUI =
            '<div class="input"><input placeholder="username" id="input_username" name="username" type="text" size="10"></div>' +
            '<div class="input"><input placeholder="password" id="input_password" name="password" type="text" size="10"></div>';
        $(basicAuthUI).insertBefore("#api_selector div.input:last-child");
        $("#input_username").change(addBasicAuthorization);
        $("#input_password").change(addBasicAuthorization);
        $("#input_apiKey").hide();
    });

    function addBasicAuthorization() {
        var username = $("#input_username").val();
        var password = $("#input_password").val();

        if (username.trim() != "" & password.trim() != "") {
            var basicAuth = new window.SwaggerClient.PasswordAuthorization('basic', username, password);
            window.swaggerUi.api.clientAuthorizations.add("basicAuth", basicAuth);
            console.log("authorization added: username = " + username + ", password = " + password);
        }
    }
})();

Here we are hiding the api_key element and adding username & password elements to the UI. Now we need to include this javascript file in Swagger; Swagger includes only Embedded resource files only. So, we have to make our javascript file as an embedded resource file. To do that, open solution explorer, right-click on the basic-authentication.js file, select properties and change Build Action property value to “Embedded Resource”.

Let’s add this basic-authentication.js file Swagger UI by adding it to Swagger config, as shown below.

using System.Web.Http;
using WebActivatorEx;
using CompanyRestAPI;
using Swashbuckle.Application;

[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]

namespace CompanyRestAPI
{
    public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {
                        c.SingleApiVersion("v1", "CompanyRestAPI").Description("This is example for Asp.Net Web API");
                        c.IncludeXmlComments(string.Format(@"{0}\bin\CompanyRestAPI.xml", System.AppDomain.CurrentDomain.BaseDirectory));
                    })
                .EnableSwaggerUi(c =>
                    {
                        c.InjectJavaScript(thisAssembly, "CompanyRestAPI.Custom.basic-authentication.js");
                    });
        }
    }
}

As shown above, we have included the javascript file to EnableSwaggerUi in the SwaggerConfig.cs file. Here CompanyRestAPI is the solution name; Custom is the folder name, and the remaining part is the file name.

Run the API and check the Swagger UI by going to https://localhost:44358/swagger/.

As shown above, Swagger UI is displaying basic authentication fields username and password in place of api_key. Enter “admin” for username and password fields and click on “Try it out”  button for the getemployees API method, it displays data as shown below.

If you request the API method without entering the username and password, it gives the response as a 401(Unauthorized) status code.

Download the API code from GitHub at https://github.com/techinfocorner/CompanyRestAPI