Configuring Swashbuckle for API key Authentication
A followup to adding Authentication Filters
Scenario
Recently, I wrote about adding custom authentication filters to a .NET MVC project. As a user of Swashbuckle, I needed to factor the filter into my swagger specs.To do this,we need to configure the Swagger configuration to include the api-key requirement information and configure the SwaggerUI configuration to inject some JavaScript.
Credit where due: much of this article is derived from a blog post by Steve Micholotti, the biggest difference being that his implementation covers both basic authentication and ApiKey authentication, while this is more focused on Api-Key authentication.
Adding logic for the UI
We'll need to add a JavaScript file as an embedded resource.
Create a folder in your project. I've named mine "CustomContent"to stick with Michelotti's example.
In that folder, add a new JavaScript file. I've named mine "api-key-header-auth.js".
Right-click the .js file in Solution Explorer and click Properties -> Build Action and set to "Embedded Resource"
Add the following code (again this is the work of Steve Michelotti). This leverages jQuery to pass the input box contents as the "api-key" key in the request header.
(function () {
$(function () {
$('#input_apiKey').off();
$('#input_apiKey').on('change', function () {
var key = this.value;
if (key && key.trim() !== '') {
swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("api-key", key, "header"));
}
});
});
})();
Configuring Swashbuckle
Edit your SwaggerConfig configurations to advertise that it's looking for an ApiKey as well as inject our JavaScript logic into the UI.
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
// Describe the location to the js to inject into the UI
// which will allow the UI to pass the expected header key
// NOTE: this is verbose for clarity in the demonstration.
var project = "MyProject.Web";
var path = "CustomContent";
var file = "api-key-header-auth.js";
var javascriptResourceLocation = $"{project}.{path}.{file}";
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
// other configurations omitted for brevity
c.ApiKey("API Key")
.Description("API Key Authentication")
.Name("api-key")
.In("header");
})
.EnableSwaggerUi(c =>
{
// other configurations omitted for brevity
c.InjectJavaScript(thisAssembly, javascriptResourceLocation);
});
}
}
Conclusion
I previously showed how to secure an API with an API key and now we've given the swagger user interface permissions to access our API controllers, given the proper API key. While these posts are not intended to encompass all security needs for an API, hopefully they have demonstrated some useful techniques.
Software Development Nerd