Friday, June 26, 2015
Customize Authentication Header in SwaggerUI using Swashbuckle

Swagger has quickly established itself as an important tool for building Web API’s for any platform. Swagger enables interactive documentation and client SDK generation/discoverability. One of the most frequently used Swagger tools is Swagger UI. Swagger UI provides automatically generated HTML assets that give you automatic documentation and even an online test tool. To see Swagger UI in action, check out their demo page.

Although Swagger/Swagger UI can be used for any platform, the Swashbuckle library makes integrating Swagger UI into a .NET Web API app a breeze. In fact, Azure API Apps specifically leverage Swagger via Swashbuckle to provide the metadata for Azure API apps.

Most of the out of the box features of Swagger work great. However, there are times when you need to customize this behavior. For example, by default Swagger UI gives you a textbox for for the “API key”. When you execute the request, it simply puts this API key into a query string variable called “api_key” as shown in the screen shot:

But what do you do if you need some other type of authentication? Perhaps you need Basic Auth or suppose the API key needs to be sent in an HTTP header rather than the query string.

Most of the online resources I found, suggest that you should simply replace the default web page by copying the original and making the changes you need. While it’s great to have this type of flexibility, the problem is that it makes it harder to keep up when new versions come out. You’d have to continually update your code (that you’ve now taken ownership of) each time a new version comes out.

What I want to do instead is to simply inject some JavaScript into the page to make this happen. This JavaScript needs to:

  • Add two textboxes to the page (one for username and one for password)
  • Remove/hide the existing textbox for API key
  • Set the Password Authorization (basic auth) header to use these values

Here are the steps to make that happen.

First, make sure the “Swashbuckle” and “Swashbuckle.Core” NuGet packages are added to your project. If you’re working in an Azure API app, they’ll already be added for you.

Next, add a new JavaScript file to your project. I’ll put this file in a folder called “CustomContent”:

Right-click this new JavaScript file and select “Properties”. Then change its “Build Action” to “Embedded Resource”.

Next, go to the SwaggerConfig.cs file that was added to your project when you added the Swashbuckle NuGet package. This file contains a ton of commented code – this is just to show you example configuration code that you can use. If you scroll down that file, you’ll see a commented method call to the InjectJavaScript() method. Right below that, I can now add this line of C# code:

   1:  c.InjectJavaScript(thisAssembly, "SwashbuckleCustomAuth.CustomContent.basic-auth.js");

Pay close attention to this string. The default namespace for my project happens to be “SwashbuckleCustomAuth”. Then I’ve put this JavaScript file in a folder called “CustomContent”. Finally, I give the name of the JS file. Make sure you’ve got this string correct so it will find the embedded resource properly.

Next, let’s have a look at the JavaScript code that we need to put in to basic-auth.js:

   1:  (function () {
   2:      $(function () {
   3:          var basicAuthUI =
   4:              '<div class="input"><input placeholder="username" id="input_username" name="username" type="text" size="10"/></div>' +
   5:              '<div class="input"><input placeholder="password" id="input_password" name="password" type="password" size="10"/></div>';
   6:          $(basicAuthUI).insertBefore('#api_selector div.input:last-child');
   7:          $("#input_apiKey").hide();
   9:          $('#input_username').change(addAuthorization);
  10:          $('#input_password').change(addAuthorization);
  11:      });
  13:      function addAuthorization() {
  14:          var username = $('#input_username').val();
  15:          var password = $('#input_password').val();
  16:          if (username && username.trim() != "" && password && password.trim() != "") {
  17:              var basicAuth = new SwaggerClient.PasswordAuthorization('basic', username, password);
  18:              window.swaggerUi.api.clientAuthorizations.add("basicAuth", basicAuth);
  19:              console.log("authorization added: username = " + username + ", password = " + password);
  20:          }
  21:      }
  22:  })();

jQuery is already part of the HTML page so we can leverage that here. I use JavaScript to create the two new textboxes I need – then I insert them as the last child of the “api_selector” form that contains these textboxes in the header. I then hide the default api key textbox since we won’t be using it. The next thing we need to ensure is that we’re setting the header correctly when the values in these textboxes change. For this we can use the SwaggerClient.PasswordAuthorization which is built into the Swagger JavaScript library. This code will ensure it’s added to the request:

In the screen shot above, I put in a username of “steve” and a password of “123”. This time when I invoke the request, you can see an Authorization header for Basic auth being sent in the HTTP request headers. Problem solved.

Alternatively, let’s say that instead of Basic Auth, you want the API key sent in the header rather than in the query string. Furthermore, let’s say you need that API header to be called “my-cool-api-key”. In that case, we don’t need to add any of our own textboxes but just repurpose the API key text box that is already there. We can add a new JavaScript file and make it an embedded resource in the exact same way that I’ve previously described. The JavaScript for that will look like this:

   1:  (function () {
   2:      $(function () {
   3:          $('#input_apiKey').off();
   4:          $('#input_apiKey').on('change', function () {
   5:              var key = this.value;
   6:              if (key && key.trim() !== '') {
   7:                  swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("my-cool-api-key", key, "header"));
   8:              }
   9:          });
  10:      });
  11:  })();

One other point that can sometimes lead to confusion. You might notice that the Swashbuckle configuration contains methods like this:

   1:  c.BasicAuth("basic").Description("Basic HTTP Authentication");

At first glance you might think/hope that will make the UI do the Basic Authentication for you – but it doesn’t. That simply changes the metadata that comes out of the Swagger schema that *informs* the user what type of authentication is being used. But if you actually want the Swagger UI to correctly execute the appropriate authentication scheme, follow the steps in this blog post if you’re working in .NET projects.

A sample solution containing these techniques (minus the *actual* authentication) can be downloaded here.

Posted On Friday, June 26, 2015 4:30 PM | Comments (0)
Friday, June 19, 2015
MVP Virtual Conference Videos

A few weeks ago I was one of the presenters for the Microsoft MVP Virtual Conference. All of the videos for the conference have recently been published to Channel 9.

There were many great talks at this virtual conference and I encourage you to check them out. My presentation was: Supercharge your Development with Azure Web Apps (formerly known as Azure Websites). My talk consisted of 12 different demos as I covered the following topics on Azure Web Apps:

  • Continuous Deployment
  • Configuration
  • Auto Scaling
  • Monitoring
  • Operations
  • SCM Admin Site
  • Extensions
  • Web Jobs
  • Azure CLI
  • Multi-Platform with Node
  • Analytics
  • Customizing the Portal
Posted On Friday, June 19, 2015 11:19 AM | Comments (0)
Wednesday, May 20, 2015
Create Node Task for Visual Studio Code

I love the new Visual Studio Code editor/IDE. It’s fast, simple, lightweight, and an overall pleasure to work with. I love being able to just “open a folder” and work with files directly – all while getting great intellisense.

One feature that is particular interesting to me is the ability to run Tasks from the IDE. These tasks can be anything from running gulp commands, to MSBuild, to most anything you can think of. Given that JavaScript – and Node in particular – is one of the sweet spots, I assumed that there would be a built-in task to run a file with Node. After all, there is native support for debugging Node code. But one thing I often like to do is to simple run a single file with node from the command line:

> node index.js

So I don’t need debugging. I want to execute Node against whatever file I have opened at the moment. It turns out this was not built-in – but the good news is that it was not difficult to add the functionality.

First, Ctrl+Shift+P to bring up the Command Palette. Then you want to type “Configure Task Runner”. That will open a “tasks.json” file which it will create in a local “.settings” directory. Inside there is a default TypeScript task along with a bunch of commented out tasks to show example of running on commands like gulp, MSBuild, etc. (and yes, just pretend that JSON actually has comments). You can remove everything in this file and just add:

	"version": "0.1.0",
	"command": "node",
	"isShellCommand": true,
	"args": ["${file}"]

One thing to notice is the this file allows tokens such as ${file} to represent the current opened file. Now Save the “tasks.json” file (if you don’t already have Auto-Save turned on) and return back to any of your JavaScript files. Now you can just bring up the Command Palette again and type “Run Task” – hit ENTER and “node” (which is what we named our task) will be the only thing in the list. Run that and the Output window will appear in split screen the the resulting output of your node file.

Yes, of course, I can just go over to a console window and type: “node index.js” as I’ve always traditionally done. But this makes it even easier/faster and let’s me stay within my IDE. Plus, this will always work against whatever file I happen to have opened at the time.

One bizarre thing I’ve found is that I don’t (yet) see any way to add multiple tasks to the “tasks.json” file - there does seem to be a way to add multiple tasks for a single command, but not multiple tasks for different commands. Hopefully, this will be a feature that is addressed in new versions of VS Code.

Posted On Wednesday, May 20, 2015 3:18 PM | Comments (3)
Sunday, April 12, 2015
CMAP–AngularUI Code Samples

Thanks to everyone for attending my presentation on AngularUI at CMAP this week. The code samples and slide deck for my presentation can be found here. Make sure to following the instructions in the file to get everything up and running.

Posted On Sunday, April 12, 2015 10:52 PM | Comments (0)
Thursday, February 5, 2015
New Pluralsight Course: AngularUI Fundamentals


I’m pleased to announce my latest Pluralsight course has been released: AngularUI Fundamentals.

The amazing rise in popularity of AngularJS has been well documented in the last couple of years. During that time AngularUI has really become the “go to” UI library for enhancing Angular apps.

This is very much a code-focused course. Throughout this course, I continue to build out the app that I showed in my previous Pluralsight course: Building Mobile Apps With the Ionic Framework and AngularJS. In the previous course, I built out the mobile app – in this course, I focus on the Admin app which is used to organize the schedule for basketball leagues/tournaments – you’ll see the Admin app built from start to finish. The admin app provided a good way to show various components like UI-Router, UI-GMap, UI-Calendar, UI-Grid, UI-Ace, and more!

Course Modules

  1. Introduction – In this module, I’ll introduce AngularUI and show the app that we’ll be building throughout the course.
  2. UI-Bootstrap – I’ll start by showing UI-Bootstrap and almost all of the components that come with it. This enables Bootstrap to be used natively with Angular, without a jQuery dependency.
  3. UI-Router – Here I’ll introduce UI-Router and show various aspects such as nested views.
  4. UI-Modules with External Dependencies – In this module, I’ll show three modules that do have external dependencies (e.g., jQuery) – UI-Calendar, UI-GMap, and UI-ACE.
  5. UI-Modules – Native – Here I’ll show modules that have full native Angular implementations with no external dependencies – UI-Grid, UI-Select, and UI-Alias.
  6. UI-Utils – In this final module, I’ll show several of the most-used UI-Utils including Keypress, Event Binder, Highlight, Mask, and others.

The following is the official description of the course:

AngularUI has established itself as the ultimate companion framework for building AngularJS applications. In this course, we'll see how to quickly get up and running with AngularUI. We will cover UI-Bootstrap so we can leverage the Bootstrap framework without a jQuery dependency. We will then dive into UI-Router to see how this powerful routing alternative can be fully leveraged in your apps. We will cover numerous modules, including UI-Calendar, UI-GMap, UI-Grid, UI-Select, and more! By the end of the course, you'll be able to start building your own apps using AngularUI on top of AngularJS!

If you want to take your AngularJS apps to the next level, then I encourage you to check out my latest course on AngularUI!

Posted On Thursday, February 5, 2015 10:50 AM | Comments (0)
Friday, October 10, 2014
CMAP – Ionic Code Samples

Thanks to everyone for attending my presentation on Building mobile apps with the Ionic framework and AngularJS at CMAP. The code samples and PowerPoint for my presentation can be found here.

Posted On Friday, October 10, 2014 10:20 AM | Comments (5)
Wednesday, September 3, 2014
New Pluralsight Course: Building Mobile Apps With the Ionic Framework and AngularJS

I’m pleased to announce that my latest Pluralsight course has been released: Building Mobile Apps With the Ionic Framework and AngularJS.

I’ve been building cross-platform mobile apps for a while now and the Ionic Framework is the most exciting mobile framework I’ve ever worked with. It’s built on top of AngularJS so all of your pre-existing Angular knowledge will transfer. Many of the concepts are similar to Bootstrap so you can almost think of Ionic as “Bootstrap for Mobile.”

This is a code-focused, demo-heavy course with a focus on building apps. Throughout the course, I build an app used to organize the schedule for basketball leagues/tournaments – so you’ll see an app built from start to finish.

Course Modules

  1. Introduction – In this module, I’ll introduce Ionic and show a preview of the app we’ll be building.
  2. Getting Started with Ionic – I’ll start by showing the Ionic command line features and show how you can run an app in the browser, emulator, and on the mobile device itself. We’ll also cover setting up your development environment.
  3. Navigation and Routing – Here I introduce Ionic components for navigation including headers, footers, and menus. I also show the Angular UI Router.
  4. Ionic Components – In this module I’ll show some of the core Ionic components including Lists, Grids, Cards, Form controls, Popups, and more.
  5. Data and Caching – Here we incorporate HTTP calls, promises, and caching for offline scenarios.
  6. Mapping – In this module, I incorporate mapping into the app including the ability to get driving directions.
  7. Customizing Ionic – Here I show how to customize Ionic with custom directives and custom SASS.
  8. ngCordova – ngCordova is a great extension to your Ionic development with puts an AngularJS-friendly wrapper around the base Cordova library. This enables easy access to device capabilities like the Camera, Barcode Scanner, GeoLocation, and more.

The following is the official description of the course:

The Ionic Framework is a tremendous step forward for quickly building Cordova-based mobile apps. Built on top of AngularJS, developers are able to leverage all of their pre-existing AngularJS skills when working with the Ionic Framework, considered by many to be the "Bootstrap for mobile." In this course, we will see how to quickly get up and running with an Ionic app in seconds. We will then cover navigation and routing, followed by demonstrations of all the primary Ionic components. We will also cover data and caching for offline functionality, as well as mapping and providing driving directions. We will finish with a review of ngCordova to easily access native device features such as the camera, barcode scanner, and more. By the end of the course, you'll be able to start building your own mobile apps using the Ionic Framework and AngularJS!

If you’re a fan of AngularJS and you are looking for a fun way to quickly build robust mobile apps, then I encourage you to check out my latest course on the Ionic Framework with AngularJS!

Posted On Wednesday, September 3, 2014 1:03 AM | Comments (3)
Tuesday, June 17, 2014
Microsoft Maniacs User Group – JS Patterns Code Samples

Thanks to everyone for attending my presentation last week on JavaScript Patterns at the new Microsoft Maniacs user group. The PowerPoint (which contains links to the code samples) can be found here.

Posted On Tuesday, June 17, 2014 3:22 PM | Comments (0)
Tuesday, May 20, 2014
Teach Your Kid to Code Coming to Philly.NET

Tomorrow night (Wednesday, May 21) my son and I will be at Philly.NET presenting Teach Your Kid to Code. Bring your kid out to Philly.NET with you for a fun evening! After our first talk, I’ll then be giving an introduction to TypeScript. Of any presentation I’ve ever given, this is my favorite:

Have you ever wanted a way to teach your kid to code? For that matter, have you ever wanted to simply be able to explain to your kid what you do for a living? Putting things in a context that a kid can understand is not as easy as it sounds. If you are someone curious about these concepts, this is a “can’t miss” presentation that will be co-presented by Justin Michelotti (6th grader) and his father. Bring your kid with you to Philly.NET for this fun and educational session. We will show tools you may not have been aware of like SmallBasic and Kodu – we’ll even throw in a little Visual Studio and JavaScript. Concepts such as variables, conditionals, loops, and functions will be covered while we introduce object oriented concepts without any of the confusing words. Kids are not required for entry!

Posted On Tuesday, May 20, 2014 9:41 PM | Comments (2)
Friday, March 14, 2014
New Pluralsight Course: Building Cross-Platform Mobile Apps with Telerik AppBuilder



I’m pleased to announce that my latest Pluralsight course has been released: Building Cross-Platform Mobile Apps with Telerik AppBuilder.

Telerik AppBuilder enables developers to easily build native-like Cordova-based (aka PhoneGap) apps with HTML/JavaScript. Mobile app development does not have to be as painstaking as it has been in previous years. Building hybrid mobile applications with JavaScript, HTML, and CSS enables you to deploy your app on multiple platforms without having to learn a new programming language for each platform. Hybrid apps enable you to re-use your existing JavaScript and HTML skills to quickly build compelling apps. Telerik AppBuilder is one of the best tools available today for building cross-platform applications. AppBuilder represents a giant leap forward for development tools for mobile apps. In this course, we will look at all of the major features of AppBuilder including the three IDEs, the robust AppBuilder simulator, debugging with AppBuilder, built-in project templates, working with plugins, Everlive services, source control, deployment, and more!

Telerik AppBuilder was formerly called Icenium and, in fact, when the Pluralsight course was first published (a few weeks ago) it was still called Icenium. Therefore, there are many references to “Icenium” during the course but the main titles have been changed. Anywhere where you see/hear a reference to “Icenium”, just substitute “Telerik AppBuilder” for the new name and know that it’s referring to the same thing. One other aspect is that in this course I focused more on the AppBuilder tool itself – and less on the underlying code. In potential future courses, I will focus more on the underlying code for mobile apps.

If you’ve been frustrated by the painstaking process of building mobile apps in the past and you are looking for a fun way to build iOS and Android App Store applications with HTML/JS then I encourage you to check out my course on Telerik AppBuilder!

Posted On Friday, March 14, 2014 1:57 PM | Comments (1)
Monday, March 3, 2014
CapArea – Durandal vs. Angular Code Samples

Thanks to everyone for attending my presentation last week on DurandalJS vs. AngularJS at CapArea. The code samples and PowerPoint from my presentation can be found here.

Posted On Monday, March 3, 2014 5:17 PM | Comments (0)
Friday, January 10, 2014
CMAP – DurandalJS Code Samples

Thanks to everyone for attending my presentation on DurandalJS. The code samples and PowerPoint from my presentation can be found here.

Posted On Friday, January 10, 2014 10:59 AM | Comments (0)
Monday, September 16, 2013
TriNug – Web API Code Samples

Thanks to everyone who attended my ASP.NET Web API presentation last week at the TriNug user group. Over 100 people at the presentation with standing room only, TriNug has truly built an amazing user group with enthusiastic members who asked engaging questions during the entire presentation. I really enjoyed my time there and look forward to returning in the future.

Code samples and PowerPoint can be found here.

Posted On Monday, September 16, 2013 10:31 AM | Comments (2)
Monday, September 2, 2013
New Pluralsight Course: .NET Micro ORMs



I’m pleased to announce that my latest Pluralsight course has been released: .NET Micro ORMs.

If you’re looking for an ORM that is simple, lightweight, and still lightening fast, then this course if for you. I start the course with a discussion of what a Micro ORM is and why you might want to use one. I also layout some of the common counter-arguments you hear against using a Micro ORM and examine the validity of each one.

There are many great open source Micro ORMs available today and it was not easy deciding which ones to include in the course. Ultimately, I included the following (each with its own module) based on their features and popularity:

Several of the Micro ORMs have similar functionality in terms of fully supporting all CRUD scenarios and working with SQL or Stored Procedures. However, diving deeper into the course, you’ll see many features you may not have known were supported by Micro ORMs. These types of features include working with complex objects, working with dynamic data, bulk inserts, automatic database table creation, supporting aggregates, metadata, automatic paging, joins, completely dynamic API, and more!

If you’re deciding on a Micro ORM to use for your next project, then I recommend watching all the modules in order to see the types of features that are supported by each one so you can determine the best fit for your project in terms of functionality and your personal preference. However, if you’ve already selected a Micro ORM, then you can watch the first Introduction module (it’s only 22 minutes) and then skip directly to the module for the Micro ORM that you’re using.

If you’ve been frustrated by your existing ORM, bring back some of the fun (and speed!) to your data access with .NET Micro ORMs!

Posted On Monday, September 2, 2013 9:41 PM | Comments (1)
Wednesday, July 24, 2013
Fun With the Chrome JavaScript Console and the Pluralsight Website

I’m currently working on my third course for Pluralsight. Everyone already knows that Scott Allen is a “dominating force” for Pluralsight but I was curious how many courses other authors have published as well. The Pluralsight Authors page - – shows all 146 authors and you can click on any author’s page to see how many (and which) courses they have authored. The problem is: I don’t want to have to click into 146 pages to get a count for each author.

With this in mind, I figured I could write a little JavaScript using the Chrome JavaScript console to do some “detective work.” My first step was to figure out how the HTML was structured on this page so I could do some screen-scraping. Right-click the first author - “Inspect Element”. I can see there is a primary <div> with a class of “main” which contains all the authors. Each author is in an <h3> with an <a> tag containing their name and link to their page:



This web page already has jQuery loaded so I can use $ directly from the console. This allows me to just use jQuery to inspect items on the current page. Notice this is a multi-line command. In order to use multiple lines in the console you have to press SHIFT-ENTER to go to the next line:



Now I can see I’m extracting data just fine. At this point I want to follow each URL. Then I want to screen-scrape this next page to see how many courses each author has done. Let’s take a look at the author detail page:




I can see we have a table (with a css class of “course”) that contains rows for each course authored. This means I can get the number of courses pretty easily like this:



Now I can put this all together. Back on the authors page, I want to follow each URL, extract the returned HTML, and grab the count. In the code below, I simply use the jQuery $.get() method to get the author detail page and the “data” variable that is in the callback contains the HTML. A nice feature of jQuery is that I can simply put this HTML string inside of $() and I can use jQuery selectors directly on it in conjunction with the find() method:



Now I’m getting somewhere. I have every Pluralsight author and how many courses each one has authored. But that’s not quite what I’m after – what I want to see are the authors that have the MOST courses in the library. What I’d like to do is to put all of the data in an array and then sort that array descending by number of courses. I can add an item to the array after each author detail page is returned but the catch here is that I can’t perform the sort operation until ALL of the author detail pages have executed. The jQuery $.get() method is naturally an async method so I essentially have 146 async calls and I don’t want to perform my sort action until ALL have completed (side note: don’t run this script too many times or the Pluralsight servers might think your an evil hacker attempting a DoS attack and deny you). My C# brain wants to use a WaitHandle WaitAll() method here but this is JavaScript.

I was able to do this by using the jQuery Deferred() object. I create a new deferred object for each request and push it onto a deferred array. After each request is complete, I signal completion by calling the resolve() method. Finally, I use a $.when.apply() method to execute my descending sort operation once all requests are complete. Here is my complete console command:

   1:  var authorList = [],
   2:      defList = [];
   3:  $(".main h3 a").each(function() { 
   4:      var def = $.Deferred();
   5:      defList.push(def);
   6:      var authorName = $(this).text();
   7:      var authorUrl = $(this).attr('href');
   8:      $.get(authorUrl, function(data) {
   9:          var courseCount = $(data).find("table.course tbody tr").length;
  10:          authorList.push({ name: authorName, numberOfCourses: courseCount });
  11:          def.resolve();
  12:      });
  13:  });
  14:  $.when.apply($, defList).then(function() {
  15:      console.log("*Everything* is complete");
  16:      var sortedList = authorList.sort(function(obj1, obj2) {
  17:          return obj2.numberOfCourses - obj1.numberOfCourses;
  18:      });
  19:      for (var i = 0; i < sortedList.length; i++) {
  20:          console.log(authorList[i]);
  21:      }
  22:  });


And here are the results:



WOW! John Sonmez has 44 courses!! And Matt Milner has 29! I guess Scott Allen isn’t the only “dominating force”. I would have assumed Scott Allen was #1 but he comes in as #3 in total course count (of course Scott has 11 courses in the Top 50, and 14 in the Top 100 which is incredible!). Given that I’m in the middle of producing only my third course, I better get to work!

Posted On Wednesday, July 24, 2013 4:11 PM | Comments (1)

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers

Google My Blog

Tag Cloud