Skip to content

Instantly share code, notes, and snippets.

@rrharvey
Last active May 5, 2019 09:39
Show Gist options
  • Save rrharvey/da1fe67cb43fe3059de2d8aa6f67a825 to your computer and use it in GitHub Desktop.
Save rrharvey/da1fe67cb43fe3059de2d8aa6f67a825 to your computer and use it in GitHub Desktop.
Add bearer token to Swagger UI using Swashbuckle
(function () {
$(function () {
$('#input_apiKey').attr('placeholder', 'JSON Web Token');
$('#input_apiKey').off();
$('#input_apiKey').on('change', function () {
var key = this.value;
console.info('Set bearer token to: ' + key);
if (key && key.trim() !== '') {
swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + key, "header"));
}
});
});
})();
using Swashbuckle.Application;
using System;
using System.Reflection;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace MyApplication
{
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
// Use "SingleApiVersion" to describe a single version API. Swagger 2.0 includes an "Info" object to
// hold additional metadata for an API. Version and title are required but you can also provide
// additional fields by chaining methods off SingleApiVersion.
//
c.SingleApiVersion("v1", "MyApplication");
})
.EnableSwaggerUi(c =>
{
// Use the "InjectJavaScript" option to invoke one or more custom JavaScripts after the swagger-ui
// has loaded. The file must be included in your project as an "Embedded Resource", and then the resource's
// "Logical Name" is passed to the method as shown above.
c.InjectJavaScript(thisAssembly, "MyApplication.CustomSwagger.js");
});
}
}
}
@lineker
Copy link

lineker commented Sep 21, 2017

works beautifully. thanks alot

@neharustagi
Copy link

Works really Well. Thanks for the solution

@janmohammadi
Copy link

janmohammadi commented Jan 1, 2018

I improved this script as flow, that can accept , in that text box.
`(function () {

function getJwt(user, pass, success, error, complete) {
    $.ajax({
        url: '/Token',
        type: 'POST',
        data: {
            grant_type: 'password',
            username: user,
            password: pass

        },
        success: function (data) {
            success && success(data.access_token);
        },
        error: function (jqXhr, err, msg) {
            error && error(JSON.parse(jqXhr.responseText).error_description);

        },
        complete: complete
    });
}
function setJwt(key) {
    swaggerUi.api.clientAuthorizations.authz = {};
    swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + key, "header"));

}


$(function () {
 
    $('#input_apiKey')
        .attr('placeholder', 'JWT | User,Pass')
        .off()
        .on('change', function () {
            var key = this.value;
            window.localStorage.setItem('key', key);

            if (key.indexOf(',') > -1) {
                var user = key.split(',')[0];
                var pass = key.split(',')[1];
                $('#input_apiKey').prop("disabled", true);
                getJwt(user, pass,
                    function (jwt) {
                        $('#input_apiKey').css('background', '#65f30f');
                        setJwt(jwt);
                    },
                    function (err) {
                        $('#input_apiKey').css('background', '#fd7474');
                        setJwt('');
                        alert(err);
                    }, function () {
                        $('#input_apiKey').prop("disabled", false);

                    });
            } else {
                $('#input_apiKey').css('background', '#FFF');

                setJwt(key);
            }


        });

    var oldKey = window.localStorage.getItem('key');
    if (oldKey) {
        $('#input_apiKey').val(oldKey).change();
    }

});

})();`

@rmarzolo
Copy link

rmarzolo commented Jan 3, 2018

@janmohammadi - that is a great solution and worked excellent! THANK YOU!

Copy link

ghost commented May 2, 2018

@janmohammadi,
can you give me more details? Where did you enter this script?
do you have an example with all distribution files?

@hariharanmurugan
Copy link

does this feature supports in v5.6?

@sdesyllas
Copy link

Works like a charm! Thanks a lot.

@mbasaran
Copy link

mbasaran commented Aug 29, 2018

This script is only Swashbuckle for .net framework that uses old version of Swagger-ui (v2.2.10). Swashbuckle ASP.NET Core (v3) uses swagger-ui v3.x.

  1. To add Jquery support, I customized swagger index.html.
  2. There is no '#input_apiKey' element. Used new selectors at CustomSwagger.js
  3. There is no 'swaggerUi.api.clientAuthorizations' so used react.js functions to set api key input.

I changed @janmohammadi 's script to support swagger-ui v3. Here is the link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment