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.

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.

publicclassSwaggerConfig{publicstaticvoidRegister(){varthisAssembly=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.varproject="MyProject.Web";varpath="CustomContent";varfile="api-key-header-auth.js";varjavascriptResourceLocation=$"{project}.{path}.{file}";GlobalConfiguration.Configuration.EnableSwagger(c=>{// other configurations omitted for brevityc.ApiKey("API Key").Description("API Key Authentication").Name("api-key").In("header");}).EnableSwaggerUi(c=>{// other configurations omitted for brevityc.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.