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");
});
}
}
}
@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