The Most Popular Articles of the Year

I suspect there may be a bunch of blog posts around the Internet that wrap up the year. Here are the most popular articles on my blog for the year:

React with ES6 and JSX

In fifth place, I did a series of articles on working with ECMAScript 2015 and React/Flux, working on getting a typical application working. I also poked into some stage0 proposals for ECMAScript7. I really enjoy working with React, but I’m torn between Custom Elements (and Polymer specifically) and React. Custom Elements are more standard – React is more popular. I’ll be revisiting this again next year (which is in 24 hours, but I’ll likely take longer than that).

Aurelia – a new framework for ES6

In fourth place, people were interested in how I would do my test tutorial with Aurelia. Aurelia is a really interesting framework and I prefer it over Ember and Angular. The learning curve is relatively small, although I will have to revisit the whole framework discussion as Angular 2 and Ember next-gen are coming out. This tutorial included using authentication with Auth0 and accessing remote resources.

ASP.NET MVC6 and Bootstrap

A one-off article on adding Bootstrap to ASP.NET MVC6 applications came in third place. There are other Bootstrap posts that are also interesting, including one that got made into a video.

Talking of ASP.NET MVC6

With the next revision of ASP.NET imminent, I took several strolls through the alpha and beta releases of that framework. There is a lot to like about it and a lot that is familiar. I’ve mostly switched over to a NodeJS environment now, so I’m not expecting to do much more in this area, but it is a much nicer environment that the old ASP.NET.

And finally, Visual Studio Tooling!

Fueled in large part by a link from the ASP.NET Community Articles page, the #1 page for the year was an article I wrote that described the Web Development extensions I used in Visual Studio. It also generated the most discussion with lots of people telling me about their favorite extensions. I’m using Visual Studio Code more these days – it’s lighter weight. I still love this list though.

Next Year

2015 was definitely the year that frameworks changed – In .NET land we got a look at the next revision of the ASP.NET framework, and in JavaScript land we got Aurelia, React, Flux, Relay, Angular-2, ES2015, Web Components, and several new versions of Node. I hope the framework releases calm down in 2016 so we can start sorting out the good from the bad and ugly. I’m going to take new looks at all this and work on my side projects. I hope you will continue the journey with me.

A Simple App with the AngularJS Framework (Part 2)

In my last post I introduced some major concepts in AngularJS development. I handled models, views and controllers and set up routing. There were a couple of things I did not do, however. The first is the menu bar and the second is authentication. Let’s cover the menu bar first.

The Menu Bar

There are lots of ways to configure a menu bar and I don’t think any one is any better than the others. I could create a custom Angular Directive that takes a DIV and turns it into my nav bar based on a template and a controller. This would be good if I were going to re-use the menu bar time and again.

Alternatively, maybe this is so common that someone else has already done it. There is a great web site – ngmodules.org – that contains a collection of Angular modules that are ready to use. This wouldn’t assist me in learning Angular.

Instead, I’m going to add my code to the main public/index.html file and create another controller. The view will be embedded in the main public/index.html file. Here is the code for the main page:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Angular Test Site</title>
		<link rel="stylesheet" href="jspm_packages/npm/font-awesome@4.3.0/css/font-awesome.min.css">
		<link rel="stylesheet" href="jspm_packages/github/twbs/bootstrap@3.3.5/css/bootstrap.min.css">
		<link rel="stylesheet" href="styles/site.css">
	</head>
	<body ng-app="testApp">
		<header ng-controller="NavBarController">
			<div id="brand">
				<div class="valign-o">
					<div class="valign-i">
						<i class="fa fa-home"></i>
						<span>{{title}}</span>
					</div>
				</div>
			</div>
			<div id="navigation">
				<ul>
					<li ng-class="{ active: isActive('/welcome')}">
						<a href="#/welcome">Welcome</a>
					</li>
					<li ng-class="{ active: isActive('/flickr')}">
						<a href="#/flickr">Flickr</a>
					</li>
				</ul>
			</div>
			<div id="toolbar">
				<ul>
					<li id="navProfile"></li>
					<li id="navSignIn">
						<i class="fa fa-sign-in"></i>
					</li>
				</ul>
			</div>
		</header>

		<div class="page-host">
			<section ng-view></section>
		</div>

		<script src="jspm_packages/github/components/jquery@2.1.4/jquery.min.js"></script>
		<script src="jspm_packages/github/twbs/bootstrap@3.3.5/js/bootstrap.min.js"></script>
		<script src="jspm_packages/github/angular/bower-angular@1.4.2/angular.min.js"></script>
		<script src="jspm_packages/github/angular/bower-angular-route@1.4.2/angular-route.min.js"></script>
		<script src="app.js"></script>
	</body>
</html>

I pretty much copied the additional markup from my Aurelia example. There are some minor tweaks to account for the difference in syntax for including specific code. In this case, I am using the isActive() method within the controller to determine whether to add the active class or not. I’ve included the sign-in toolbar and will get to that in the next section – it’s not necessary for the navigation to work. I use a named controller with the ng-controller directive to wire up my controller to this view.

If I compare this to Aurelia, then I did the same thing in the app.html file – that file became the template for my overall page. In Angular, the root document is the template for my overall page.

I already know how to create a controller, so let’s take a look (thanks to myl on Stack Overflow for this code). I added this to the app.js file:

testApp.controller("NavBarController", [ "$scope", "$location",
	function NavBarController ($scope, $location) {
		$scope.title = "Angular";
		
		$scope.isActive = function (viewLocation) {
			return viewLocation === $location.path();
		};
	}
]);

This does what is expected. I would love, however, to have the nav-bar separated. To do that, I need to write a custom Angular Directive. Here is the code within app.js:

testApp.directive("ngNavbar", function () {
	return {
		restrict: "A",
		templateUrl: "partials/navbar.html"
	}
});

This defines an Attribute (restrict: "A") that I can place on another HTML element. When I put the ng-navbar attribute on that element, its innerHTML will be populated with the template I have specified. I need to create that navbar.html file:

<header>
	<div id="brand">
		<div class="valign-o">
			<div class="valign-i">
				<i class="fa fa-home"></i>
				<span>{{title}}</span>
			</div>
		</div>
	</div>
	<div id="navigation">
		<ul>
			<li ng-class="{ active: isActive('/welcome')}">
				<a href="#/welcome">Welcome</a>
			</li>
			<li ng-class="{ active: isActive('/flickr')}">
				<a href="#/flickr">Flickr</a>
			</li>
		</ul>
	</div>
	<div id="toolbar">
		<ul>
			<li id="navProfile"></li>
			<li id="navSignIn">
				<i class="fa fa-sign-in"></i>
			</li>
		</ul>
	</div>
</header>

This is exactly the same code as was wrapped inside the public/index.html file. Now I can remove that code from the public/index.html file:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Angular Test Site</title>
		<link rel="stylesheet" href="jspm_packages/npm/font-awesome@4.3.0/css/font-awesome.min.css">
		<link rel="stylesheet" href="jspm_packages/github/twbs/bootstrap@3.3.5/css/bootstrap.min.css">
		<link rel="stylesheet" href="styles/site.css">
	</head>
	<body ng-app="testApp">
		<div ng-controller="NavBarController" ng-navbar></div>

		<div class="page-host">
			<section ng-view></section>
		</div>

		<script src="jspm_packages/github/components/jquery@2.1.4/jquery.min.js"></script>
		<script src="jspm_packages/github/twbs/bootstrap@3.3.5/js/bootstrap.min.js"></script>
		<script src="jspm_packages/github/angular/bower-angular@1.4.2/angular.min.js"></script>
		<script src="jspm_packages/github/angular/bower-angular-route@1.4.2/angular-route.min.js"></script>
		<script src="app.js"></script>
	</body>
</html>

This makes the code much more readable. I could also place the controller in the angular directive I’ve just created as well – a task for another time.

Authentication

As I am doing for the other projects, I’m going to use Auth0 for authentication here. Auth0 has provided an excellent tutorial for this purpose, so I am only going to note the differences.

Installing the libraries was mostly done with jspm:

jspm install angular-cookies
jspm install github:auth0/angular-storage
jspm install github:auth0/angular-jwt

The public/index.html file became the following:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Angular Test Site</title>
		<link rel="stylesheet" href="jspm_packages/npm/font-awesome@4.3.0/css/font-awesome.min.css">
		<link rel="stylesheet" href="jspm_packages/github/twbs/bootstrap@3.3.5/css/bootstrap.min.css">
		<link rel="stylesheet" href="styles/site.css">
	</head>
	<body ng-app="testApp">
		<div ng-controller="NavBarController" ng-navbar></div>

		<div class="page-host">
			<section ng-view></section>
		</div>

		<script src="jspm_packages/github/components/jquery@2.1.4/jquery.min.js"></script>
		<script src="jspm_packages/github/twbs/bootstrap@3.3.5/js/bootstrap.min.js"></script>
		<script src="jspm_packages/github/angular/bower-angular@1.4.2/angular.min.js"></script>
		<script src="jspm_packages/github/angular/bower-angular-route@1.4.2/angular-route.min.js"></script>
		<script src="jspm_packages/github/angular/bower-angular-cookies@1.4.2/angular-cookies.min.js"></script>
		<script src="jspm_packages/github/auth0/angular-storage@0.0.11/dist/angular-storage.min.js"></script>
		<script src="jspm_packages/github/auth0/angular-jwt@0.0.9/dist/angular-jwt.min.js"></script>
		<script src="http://cdn.auth0.com/js/lock-7.5.min.js"></script>
		<script src="http://cdn.auth0.com/w2auth0-angular-4.js"></script>
		
		<script src="app.js"></script>
	</body>
</html>

That’s lots of scripts at this point – I’d probably handle this with Browserify or some other sort of bundling technology in a production app. This is good for right now. Note that I’m downloading a couple of the libraries from the Auth0 CDN – I’d probably look into bringing these in as local libraries as well. Auth0 publishes lock on their GitHub page.

The partials/navbar.html page also needed a change – I’ve highlighted the changed lines:

<header>
	<div id="brand">
		<div class="valign-o">
			<div class="valign-i">
				<i class="fa fa-home"></i>
				<span>{{title}}</span>
			</div>
		</div>
	</div>
	<div id="navigation">
		<ul>
			<li ng-class="{ active: isActive('/welcome')}">
				<a href="#/welcome">Welcome</a>
			</li>
			<li ng-class="{ active: isActive('/flickr')}">
				<a href="#/flickr">Flickr</a>
			</li>
		</ul>
	</div>
	<div id="toolbar">
		<ul>
			<li id="navProfile">{{nickname}}</li>
			<li id="navSignIn" ng-click="login()">
				<i class="fa fa-{{icon}}"></i>
			</li>
		</ul>
	</div>
</header>

Lines 22 and 24 bind specific variables in the $scope of the NavbarController to these areas. Line 23 uses the ng-click event handler to call the login method in the NavbarController.

Moving on to the app.js, there are two things I must do. Firstly, I have to configure the module and Angular application for authentication. This is straight from the Auth0 Quick Start Guide:

var testApp = angular.module("testApp", [ 'ngRoute', 'auth0', 'angular-storage', 'angular-jwt' ]);

testApp.config(["$routeProvider", "authProvider", function($routeProvider, authProvider) {
	// Route Map
	$routeProvider
		.when("/welcome", {
			title: "Welcome",
			templateUrl: "partials/welcome.html",
			controller: "WelcomeController"
		})
		.when("/flickr", {
			title: "Flickr",
			templateUrl: "partials/flickr.html",
			controller: "FlickrController"
		})
		.otherwise({
			redirectTo: "/welcome"
		});

	authProvider.init({
		domain: "DOMAIN.auth0.com",
		clientID: "YOUR-CLIENT-ID"
	});
}]);

// This hooks all auth events to check everything as soon as the app starts
testApp.run(function (auth) {
	auth.hookEvents();
});

Line 3 brings in all those libraries that Auth0 said I needed. Line 5 adds the authProvider via dependency injection. The authProvider is provided by Auth0. Line 22-25 actually configures the Auth0 settings. Remember to inject your own domain and clientID here. Finally, line 29-31 ensures all the authentication events are captured as the application starts.

The other area of concern is the NavbarController. Here is the new one:

testApp.controller("NavBarController", [ "$scope", "$http", "auth", "store", "$location",
	function NavBarController ($scope, $http, auth, store, $location) {
		$scope.title = "Angular";
		$scope.nickname = "";
		$scope.icon = "sign-in";

		$scope.isActive = function (viewLocation) {
			return viewLocation === $location.path();
		};

		var profile = store.get("profile");
		if (profile) {
			$scope.nickname = profile.name || profile.nickname;
			$scope.icon = "sign-out";
		};

		$scope.login = function() {
			if ($scope.icon === "sign-out") {
				$scope.nickname = "";
				$scope.icon = "sign-in";
				auth.signout();
				store.remove("profile");
				store.remove("token");
			} else {
				auth.signin({}, function (profile, token) {
					// Success callback
					store.set("profile", profile);
					$scope.nickname = profile.name || profile.nickname;
					store.set("token", token);
					$scope.icon = "sign-out";
					$location.path("/");
				}, function () {
					// Error callback
					alert("Auth0 Error!!!!");
				});
			}
		}
	}
]);

There are two new scope variables. The $scope.nickname will be blank when the user is not logged in and will be filled with something when the user is logged in. The $scope.icon will either be “sign-in” or “sign-out” – this changes the icon that is displayed.

From line 82-86, I set up the initial values of the nickname and icon based on the localStorage (represented by the store variable). The default case is the user is unauthenticated. As a result, I only need to change things if the user is authenticated – i.e. when something is in the profile.

The $scope.login() method is called when the user clicks on the authenticator icon. If the user is signed in, then the user is logged out. If the user is not signed in, then I pop up the Auth0 sign-in window and wait for soemthing to come back. A successful return means that the user is logged in, so I store the token and profile and update the nav bar view.

An Authenticated Page

In my Aurelia review, I added an authenticated page. This page only appeared in the navigation when I was authenticated. It also grabbed data from the backend and displayed it. I wanted the same thing here. First of all, I need an authenticated Web API – changes to server.js:

var express = require("express"),
	jwt = require("express-jwt"),
	morgan = require("morgan"),
	staticFiles = require("serve-static"),
	spells = require("./spells.json"),
	config = require("./config.json");

var app = express();

// Check that the JWT is signed by us
var jwtCheck = jwt({
  secret: new Buffer(config.clientSecret, 'base64'),
  audience: config.clientID
});

// Set the port to listen on
app.set("port", process.env.PORT || 3000);

// Set up logging
app.use(morgan("combined"));

// Set up static files within public
app.use(staticFiles("public"));

// Set up a JWT Check for the /api/spells layer
app.use("/api/spells", jwtCheck);

// Set up the spells endpoint
app.get("/api/spells", function (request, response) {
	response.send(spells);
});


// Listen on the TCP port
app.listen(app.get("port"), function () {
	console.log("Listening on port " + app.get("port"));
});

The spells.json file will be returned when I send an authenticated request to the backend for URI /api/spells. An authenticated request is a request with a valid JSON Web Token in the Authorization header. Your config.json should look like this:

{
	"domain": "YOUR-DOMAIN.auth0.com",
	"clientID": "YOUR-CLIENT-ID",
	"clientSecret": "YOUR-CLIENT-SECRET"
}

Ensure you replace the appropriate values from your configuration in Auth0. Now that I have an authenticated API, I need to display it. Firstly, let’s create a new route for “/spells” to go to the new page:

testApp.config(["$routeProvider", "authProvider",
	 function($routeProvider, authProvider) {
		// Route Map
		$routeProvider
			.when("/welcome", {
				title: "Welcome",
				templateUrl: "partials/welcome.html",
				controller: "WelcomeController"
			})
			.when("/flickr", {
				title: "Flickr",
				templateUrl: "partials/flickr.html",
				controller: "FlickrController"
			})
			.when("/spells", {
				title: "Spells",
				templateUrl: "partials/spells.html",
				controller: "SpellsController"
			})
			.otherwise({
				redirectTo: "/welcome"
			});

		authProvider.init({
			domain: "YOUR-DOMAIN.auth0.com",
			clientID: "YOUR-CLIENT-ID"
		});
	}
]);

Lines 19-23 add the new route to the spells page. I also need a Controller and a View. The Controller is as follows:

testApp.controller("SpellsController", [ "$scope", "$http", "auth", "store",
	function SpellsController ($scope, $http, auth, store) {
		$scope.heading = "Spells";
		$scope.spells = [];
		var url = "/api/spells";
		var headers = {
			"Accept": "application/json"
		};

		// Add the authorization token if we are authenticated
		if (auth.isAuthenticated) {
			headers.Authorization = "Bearer " + store.get("token");
		}

		$http.get(url, {
			"withCredentials": true,
			"responseType": "json",
			"headers": headers
		}).success(function (data, status, headers, config) {
			$scope.spells = data;
		}).error(function () {
			console.error("Error retrieving spells");
		});
	}
]);

The “magic” (such that it is) is in lines 89-91 – if the user is authenticated, I add an Authorization header with the JSON Web Token in it. That is sent with the normal headers. Once the response comes back, I assign the result to the spells variable in the scope. My partials/spells.html view is simple:

<h2>{{heading}}</h2>

<div id="spellList">
	<ul>
		<li ng-repeat="spell in spells">
			{{spell.id}}
		</li>
	</ul>
</div>

The spells variable in the scope is an array. I iterate over that array, pulling out the ID. You should get a bullet list of numbers when this is working.

There are a couple of problems with this version of the code (although it does work). Firstly, the Spells link shows up even when the user is not authenticated. This means that you will see the error message in the console. Secondly, the user gets logged out on page refreshes. This is less than ideal. Fortunately, Auth0 has provided a recipe for the latter issue. Place the following in your app.js file:

// This hooks all auth events to check everything as soon as the app starts
testApp.run([ "$rootScope", "auth", "store", "jwtHelper", "$location",
	function ($rootScope, auth, store, jwtHelper, $location) {
		auth.hookEvents();

		$rootScope.$on("$locationChangeStart", function() {
			var token = store.get("token");
			if (token) {
				if (!jwtHelper.isTokenExpired(token)) {
					if (!auth.isAuthenticated) {
						auth.authenticate(store.get("profile"), token);
					}
				} else {
					$location.path("/");
				}
			}
		});
	}
]);

This code replaces the testApp.run() method. It’s a little different than the version provided by Auth0 – this version takes advantage of the dependency injection in AngularJS v1.4. The version provided by Auth0 is for AngularJS v1.2.

This leaves making the Spells link disappear in the navigation. I already have the auth variable available in the NavBarController so I can create a new isAuthenticated() method and use it the same way as I did the isActive() method:

		$scope.isAuthenticated = function() {
			return auth.isAuthenticated;
		};

Now I can adjust the partials/navbar.html to change the Spells link to be authenticated.

<li ng-class="{ active: isActive('/spells'), 'auth-hide': !isAuthenticated()}">
  <a href="#/spells">Spells</a>
</li>

The auth-hide class is defined in styles/site.css to set display: none.

Note how I check authentication in multiple places. This goes to the “don’t trust the user” principal. I ensure the user can’t see the Spells area. If, however, the user has bookmarked the URI, then I ensure that the authentication is not passed to the backend and hence the data is not shown. If I were being particularly paranoid, I would ensure that a different message was shown and the request was not sent to the backend.

Wrapping Up

That’s it for the Angular test. Over the course of the last two posts, I’ve created controllers, views, routing, authentication and custom directives. This is definitely more complex than Aurelia, but it also has a bigger community, better support (including books, videos, tutorials) and more features. If I were deciding on something other than my own project, I would likely use AngularJS over Aurelia. (This is, of course, before I have investigated Ember, Meteor or React/Flux).

There is a big thing coming though. Angular 2 is the “next version of Angular” and promises to utilize all the features of ECMAScript 6. This warrants it’s own investigation once the code base is a little further along. However, it’s a forklift upgrade, although the Angular team says they will support “Incremental” updates by installing both Angular 1.x and 2.x at the same time. It doesn’t sound ideal.

If you want the code from my small tutorial here, it’s on my GitHub Repository.

MVC, MVVM and Frameworks

I’ve been writing a whole bunch about MVC architectures – client side and server side.  But I hit a problem.  You see, MVC and MVVM are pretty simple concepts.  Here is a typical diagram that I see when looking at MVC descriptions:

blog-08012015-1

It’s nice and simple.  The controller loads the model and passes some form of data to the View.  The problem is this – where is the user and where is the data?  How do these actually interact?  This is actually a key point in understanding the architecture and the place that frameworks – any framework – occupies in the architecture.  I think the following is a much more representative architectural diagram:

blog-08012015-2

This makes more sense to me.  The user submits a request to a dispatcher.  The dispatcher decides which controller to pass the request to.  The controller asks the adapter to give it one or more models to complete the request.  In the case of MVVM, these models are transitioned into a View-Model, usually through some sort of data binding.  This new model (or view-model) is passed into the View rendering system, which renders the appropriate view and kicks it back to the core dispatcher so that the dispatcher can respond to the user.

It’s much more messy than the plain MVC (or MVVM) design pattern.  However, it’s implementable and I can see the pieces I need to implement in order to achieve the desired web application.  This architecture can be implemented on the client side or the server side and both sides have frameworks that assist.

Frameworks provide some sort of functionality that allow you to ignore the boiler-plate code that inevitably comes with writing such an architecture.  Most frameworks have some sort of dispatcher (normally called a router, but they do much more than that) and most frameworks have some sort of adapter logic (mostly called an ORM or Object Relational Mapper).  In between, frameworks enforce a pattern for controllers, models and views that can be used to enforce consistency across the application.

On the server side, I have two go-to languages – C# and JavaScript.  I use ASP.NET as my framework of choice on the C# server side.  I can map my visual directly to ASP.NET:

  • ASP.NET provides the dispatcher, with an ability to configure a route map in it’s startup class.
  • The Controller class can be inherited to create custom controllers
  • The Model is a plain-old class
  • The View is handled by Razor syntax
  • The Adapter is generally handled by Entity Framework.

For server-side JavaScript, the mapping is a little more messy:

I haven’t really gotten into Models and Adapters, although I can see libraries such as Mongoose (for MongoDB) playing a part there.  However, there are Node/Express MVC frameworks out there – I want to investigate Locomotive and SailsJS at some point, for example.

On the client side, things are definitely more messy.  There are a host of different frameworks – Angular, Aurelia, Ember, Knockout, Meteor, React / Flux, along with a host of others.  I’ve found the TodoMVC site to have a good list of frameworks worth looking at.  Some of these are being upgraded to handle ES2015 syntax, some are already there and some are never going to be there.

One thing to note about frameworks.  They are all opinionated.  ASP.NET likes the controllers to be in a Controllers namespace.  Angular likes you to use directives.  Aurelia likes SystemJS and jspm.  Whatever it is, you need to know those opinions and how they will affect things.

The web isn’t the only place one can use frameworks.  The MVC architecture is not limited to web development – it’s constant across applications of any complexity.  For example, you can see MVC in WinForms, Mobile applications, Mac OSX Applications and Linux Applications.

I want my application to be rendered client-side, which means I need to take a look at client-side frameworks.  My working list is:

I’m not going to bother with Backbone, Meteor, Knockout or any other older or smaller framework.  This is my own time and I don’t want to spend a ton of time on investigation.  I pretty much know what Aurelia can provide.  To investigate the others I needed a small site I could implement – something that wasn’t “just another task organizer” (TodoMVC).  To that end, I decided to create a three page application.

  • Page 1 – the home page – will get loaded initially and contain a Polymer-based carousel
  • Page 2 – a linked page – will load data from the Internet (the Flickr example from the Aurelia app)
  • Page 3 – an authenticated page – will load data from the local server if the user is authenticated

In addition to the three pages, I’m going to ensure that the navigation is separated logically from the actual pages and that – where possible – the pages are written in ES2015.  I want separation of concerns, so I expect the models to be completely separate from the views and controllers.

Each one will be implemented on top of a Node/ExpressJS server that serves up just the stuff needed.  In this way, I will be able to see the install specifics.  You can see my starter project on my GitHub Repository.  I hope you will enjoy this series of blog posts as I cover each framework.

The Lifecycle of an Aurelia Custom Element

I’ve been working with Aurelia pretty well recently, but I came across a problem early on. I had some code within my navigation bar (which is a custom element) and I wanted to manipulate the DOM on startup so that my initial state was correct. So, here was my code:

import {Authenticator} from "../lib/Authenticator";

export class NavBar {
    public constructor() {
        this.setIcon(Authenticator.isAuthenticated());
    }

    public setIcon(isAuthenticated: boolean): void {
        let appToolbar = document.getElementById("appToolbar");
        let elements = document.querySelectorAll(".sign-in,.sign-out");
        // Do something with the elements list
    }
}

This is pretty simple. My Authenticator object has a static method that returns true or false depending on if I am authenticated or not. It doesn’t work. I get an exception in the Javascript console at the highlighted line. The problem is that the DOM isn’t ready when the object is instantiated.

So, how do we fix this? Well, we need to know a little bit about the underlying code and the lifecycle functions that Aurelia uses on custom elements. Firstly, let’s do a little experiment. I replaced the code above with this:

import {Authenticator} from "../lib/Authenticator";

export class NavBar {
    public constructor() {
        //this.setIcon(Authenticator.isAuthenticated());
    }

    public attached() {
        this.checkit("attached");
    }

    public activated() {
        this.checkit("activated");
    }

    public created() {
        this.checkit("created");
    }

    public activate() {
        this.checkit("activate");
    }

    public canActivate() {
        this.checkit("canActivate");
    }

    public checkit(fn: string) {
        let appToolbar = document.getElementById("appToolbar");
        console.log("[NavBar] %s %o", fn, appToolbar);
    }

    public setIcon(isAuthenticated: boolean): void {
        let appToolbar = document.getElementById("appToolbar");
        let elements = document.querySelectorAll(".sign-in,.sign-out");
        // Do something with the elements list
    }
}

I basically guessed at the lifecycle functions on the initialization side of the fence. Each one calls checkit that then checks whether the DOM is ready (as referenced by looking for an element inside the DOM of the custom element) and then prints out the method that was called and the result of the check. Since I am printing the object, I can expand the object within the console and see what else is there. Here is what I got:

blog-0717-1

Note the highlighted lines. Aurelia calls created() first, but the DOM is not available at this point. It calls attached() next and then the DOM is ready – we have a DOM element as a result of our query.

It turns out I am not the only one here. There is a bug against the documentation asking that this be included in the documentation. But it begs the question – what other lifecycle methods do I have access to? The custom elements in Aurelia are based on Web Components (see an introduction here). the webcomponents.js polyfill has four lifecycle callbacks:

  1. createdCallback
  2. attachedCallback
  3. detachedCallback
  4. attributeChangedCallback

The createdCallback will call create(); the attachedCallback will call attached(). I’m guessing the detachedCallback calls detached() but I don’t have any documentation for that. The attributeChangedCallback is handled differently. When an attribute changes, a specific method for the attribute is called.

As a result of this investigation, I can now re-code my nav-bar.ts as follows:

import {Authenticator} from "../lib/Authenticator";

export class NavBar {
    public attached() {
        this.setIcon(Authenticator.isAuthenticated());
    }

    public setIcon(isAuthenticated: boolean): void {
        let appToolbar = document.getElementById("appToolbar");
        let elements = document.querySelectorAll(".sign-in,.sign-out");
        // Do something with the elements list
    }
}

Just remember – if you want to modify the DOM in your custom element, do it in the attached() method of your custom element class.

Adding App Insights to An Aurelia App

I just finished watching some videos from Build 2015 on Channel 9. One of the topics that intrigued me was App Insights. Here I could easily add telemetry for applications in the wild and have it stored out in the cloud. Splunk Cloud gives you much the same thing without the nice UI that Azure provides, but the ease at which you could instrument an application was notable. Best of all, App Insights is free unless you have a large application or want streaming results.

To start, you need to have an Azure Subscription. You can get those for free as well. I use a Pay-as-you-go subscription so I’m only paying for what I use.

Step 1 – Create an App Insights Resource

Log in to https://portal.azure.com with your Azure credentials and click on the shiny + New button in the top left corner.

blog-0716-1

Click on Application Insights. Enter a name for your project. I generally use the project name (so in this case, it’s aurelia-2).

blog-0716-2

Click on Configure required settings. In the Application Type, click on ASP.NET web application.

blog-0716-3

Finally, click on Create. The Azure backend will go off and create the resource for you. It should open automatically when it’s done. If not, you can always open it yourself (use the Browse All button). This is what the screen looks like:

blog-0716-4

I haven’t sent any data to it, nor have I configured the aurelia-2 application yet, so this is to be expected. Note the circled cloud type icon. Clicking on that will open up a Quickstart guide. One of those guides is to Add code to monitor web pages.

Unfortunately, because Aurelia is a single page application, this code won’t work for me. However, I can place this code in my router to effect the same information.

Step 2 – Update the Aurelia Router

Handling Aurelia applications is difficult because Aurelia uses the location hash (that is, the bit after # in the URL) as a routing indicator. This bit is ignored by App Insights so I have to code around it. Let’s start in app.ts adding a new class called AppInsights:

class AppInsights {
    private server: any;

    constructor() {
        // Copy lines 9-15 from the App Insights QuickStart to here
        this.server = window.appInsights || function (config) {
            function s(config) { t[config] = function () { var i = arguments; t.queue.push(function () { t[config].apply(t, i) }) } } var t = { config: config }, r = document, f = window, e = "script", o = r.createElement(e), i, u; for (o.src = config.url || "//az416426.vo.msecnd.net/scripts/a/ai.0.js", r.getElementsByTagName(e)[0].parentNode.appendChild(o), t.cookie = r.cookie, t.queue = [], i = ["Event", "Exception", "Metric", "PageView", "Trace"]; i.length;)s("track" + i.pop()); return config.disableExceptionTracking || (i = "onerror", s("_" + i), u = f[i], f[i] = function (config, r, f, e, o) { var s = u && u(config, r, f, e, o); return s !== !0 && t["_" + i](config, r, f, e, o), s }), t
        } ({
            instrumentationKey: "{{INSTRUMENTKEY}}"
            });
        window.appInsights = this.server;
    }

    run(routingContext, next) {
        console.dir(routingContext);
        console.dir(window.location.href);
        return next();
    }
}

This code is cut and paste from the Quickstart guide on the Azure Portal, with one exception. Instead of storing the variable within an appInsights variable, I’ve stored it in a private server variable. I’ve also assigned the same code to the window.appInsights variable just in case, but that strictly isn’t necessary since the pipeline is only created once. Don’t forget to include your instrument key in this code. Mine is checked in without an instrument key.

I also need to add the class to the modelbind pipeline:

    configureRouter(config, router) {
        config.title = 'Aurelia';

        config.addPipelineStep('authorize', AuthorizeStep);
        config.addPipelineStep('modelbind', AppInsights);

        config.map([

Just like the authorization class, Aurelia calls the run() method with a routing context. I’ve just dumped everything out to the console for now so we can take a look at the objects. Run this project to see what you get.

Click around and watch the console. You will always see something after the #. I can also take a look at the routingContext.nextInstruction.moduleId to see what page is being loaded. The best idea, however, may be just to remove the # (correcting for double-slashes) and then send that to the App Insights Service. My run() method is changed to this:

    run(routingContext, next) {
        var origin = window.location.pathname + window.location.hash;
        var path = origin.replace("/#/", "/").replace("#", "");
        console.log("[AppInsights] Tracking for %s", path);
        this.server.trackPageView(path);
        return next();
    }

You can find early details of the App Insights Javascript API in the MSDN forums.

If you run the project now and click around, you’ll generate some data. Go over to the Azure Portal and you will see one chart is filled in. The interesting data, however, is in the Users, Sessions and Page views boxes. Note you can check out which pages have been used the most. They will appear without the # in them.

Wrapping Up

There are other things you can do. You could add App Insights Telemetry to your ASP.NET API, time the flickr API response and log that as a metric, or store the user that is actually logging in so that user usage is tracked properly. Really, it depends on what you want to see. However, this is a free method of getting usage statistics for your single-page Aurelia application.

As always, my code is on GitHub.

Writing Custom Middleware for ASP.NET

In my last article I decoded a JSON Web Token to get the authorization information. This was a follow on from my prior articles about submitting a JSON Web Token via the Aurelia HTTP Client, authenticating the client side in Aurelia using the Auth0 service, and getting a JSON Web Token from Auth0. However, I left the token decoding a little unfinished. Yes, I decoded a token, but from within an ASP.NET Controller. The normal way to do authorization is with middleware.

Sidestepping – Middleware?

When you do a request to an ASP.NET Web Application (whether it be standalone, MVC or WebAPI), your request goes through a series of software “pipes”. Pipes can handle the request, response or both and modify either. You are already familiar with a pipe – the ASP.NET MVC handler is an example of a pipe. ASP.NET Identity is also a pipe. These pipes are called middleware. They are configured in the Configure method of the Startup.cs like this:

        public void Configure(IApplicationBuilder app)
        {
            app.UseErrorPage(ErrorPageOptions.ShowAll);
            app.UseStaticFiles();
            app.UseJsonWebTokenAuthorization();
            app.UseMvc();
        }

The highlighted line configures the new middleware. It doesn’t exist yet, so expect a red squiggly line.

Injecting Middleware

To inject that JsonWebTokenAuthorization middleware I have to write an extension class that allows me to inject it. I’ve created a folder called Middleware and created a file called JWTExtensions.cs in that folder with the following contents:

using aurelia_2.Middleware;

namespace Microsoft.AspNet.Builder
{
    public static class JWTExtensions
    {
        public static IApplicationBuilder UseJsonWebTokenAuthorization(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<JsonWebTokenAuthorization>();
        }
    }
}

The highlighted line creates an object from the JsonWebTokenAuthorization class (this is our middleware) and tells the ASP.NET pipeline builder to use it as middleware. The JsonWebTokenAuthorization will be underlined in that red squiggly line because we haven’t written any middleware yet.

A Simple Middleware Example

I needed to create a simple middleware example for investigation. What did the middleware get fed? Could I access everything I needed to access? Questions like this are really only answered by setting a breakpoint and looking at the data. I created a JsonWebTokenAuthorization.cs class in the Middleware folder with these contents:

using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;

namespace aurelia_2.Middleware
{
    public class JsonWebTokenAuthorization
    {
        private readonly RequestDelegate next;

        public JsonWebTokenAuthorization(RequestDelegate next)
        {
            this.next = next;
        }

        public Task Invoke(HttpContext context)
        {
            Debug.WriteLine("In JsonWebTokenAuthorization.Invoke");
            return next(context);
        }
    }
}

The Debug.Writeline is only there to set a breakpoint on. In the final version, I’ll remove the System.Diagnostics and Debug.WriteLine lines. This middleware is as basic as it gets. The pipeline calls Invoke with a HttpContext (which is a wrapper for the request, response, identity, etc.) and then you call the next thing in the pipeline.

You can run this application. After clicking Continue a few times, click on the Spells link and you will be able to investigate the request that is important to you:

blog-0714-1

Note the context.Request.Headers contains the information you are after. This gives me enough information to decode the JWT and add it to my context

Decoding The Json Web Token in Middleware

Here is my replacement Invoke method in the JsonWebTokenAuthorization file:

        public Task Invoke(HttpContext context)
        {
            if (context.Request.Headers.ContainsKey("Authorization"))
            {
                var authHeader = context.Request.Headers["Authorization"];
                var authBits = authHeader.Split(' ');
                if (authBits.Length != 2)
                {
                    Debug.WriteLine("[JsonWebTokenAuthorization] Ignoring Bad Authorization Header (count!=2)");
                    return next(context);
                }
                if (!authBits[0].ToLowerInvariant().Equals("bearer"))
                {
                    Debug.WriteLine("[JsonWebTokenAuthorization] Ignoring Bad Authorization Header (type!=bearer)");
                    return next(context);
                }

                string claims;
                try
                {
                    var b64secret = config.Get("Auth0:ClientSecret").Replace('_', '/').Replace('-', '+');
                    var secret = System.Convert.FromBase64String(b64secret);
                    claims = JWT.JsonWebToken.Decode(authBits[1], secret);
                }
                catch (JWT.SignatureVerificationException)
                {
                    Debug.WriteLine("[JsonWebTokenAuthorization] Ignoring Bad Authorization (JWT signature doesn't match)");
                    return next(context);
                }
                catch (FormatException)
                {
                    Debug.WriteLine("[JsonWebTokenAuthorization] Ignoring Bad Client Secret");
                    return next(context);
                }

                Debug.WriteLine(string.Format("[JsonWebTokenAuthorization] JWT Decoded as {0}", claims));
            }
            Debug.WriteLine("In JsonWebTokenAuthorization.Invoke");
            return next(context);
        }

A log of this code is identical to the code I wrote in the last article. I’ve somewhat tightened it up by writing out error messages to the log (instead of sending an error to the user) and trapping exceptions that library routines generate on a bad Authorization header or configuration. I’ve also adjusted the constructor for this class as follows:

        private readonly RequestDelegate next;
        private readonly IConfiguration config;

        public JsonWebTokenAuthorization(RequestDelegate next)
        {
            this.next = next;
            this.config = Startup.Configuration;
        }

This is most definitely not the best way to configure an ASP.NET middleware class. This works for now and I’ll get to configuration another time. Note that the decode will fail if the JWT is expired, so I don’t have to worry about checking for an expiry time.

Creating an Identity

Eventually, I want my Controller to have an [Authorize] decorator on it. This tells the ASP.NET MVC system that it needs to authorize the user and not call the method if the user is not authorized. The Authorize decorator is actually defined in the class AuthorizeAttribute. That’s a complicated beast, able to handle users, roles and ad-hoc policies and is contained within the Microsoft.AspNet.Authorization namespace. Check out the source code. The basic premise we are after is contained in the DenyAnonymousAuthorizationRequirement.cs class. That class is actually fairly reasonable and it basically says “the user is authorized if any Identity object in the Identities list is authenticated.

That means what I have to do is create an Identity with a specific claim (pulled from the sub field of the JWT claim) and then set the IsAuthenticated flag on that Identity. Finally, I need to add the Identity to the list of Identities in the request. Here is the code:

                var identity = new ClaimsIdentity(
                    new[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, claims, xmlString, "JWT-Issuer"),
                        new Claim(ClaimTypes.Name, claims, xmlString, "JWT-Issuer"),
                    },
                    "JWT-Issuer",
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                context.User.AddIdentity(identity);

I copied this code from the Twitter code within the AspNet.Security package. XmlString is a constant that I’ve defined at the top of the class to be http://www.w3.org/2001/XMLSchema#string.

Now I can change the code in SpellsController to this:

        [Authorize]
        [Route("")]
        public string GetAll()
        {
            return "{id:1}";
        }

Running the project will do two things:

  1. If I’m signed out, the WebAPI call will return a 401 Unauthenticated response code – I can use this in my Aurelia app to trigger an authentication.
  2. If I’m signed in, the WebAPI call will return the expected JSON string.

The “claim” is in the Name of the identity and that’s a composite JSON object. You can see it using the JSON Visualizer in Visual Studio. Set a breakpoint on the Debug.WriteLine that says JWT Decoded. When it is hit, go to the Locals tab and expand the identity. Click on the down-arrow on the right hand side of the row that shows the Name property, then select JSON Visualizer. You will get something like this:

blog-0715-1

Decoding the JSON Response

I really want to have the JWT-Issuer replaced by the iss (or Issuer) field and the name replaced by the sub (or Subject) field. Now that I have a plaintext token that I have verified, I can trust that it has not been mutilated in transit. This allows me to use a standard mechanism to decode it:

                var jwt = JsonConvert.DeserializeObject<JsonWebToken>(claims,new JsonSerializerSettings
                {
                    MissingMemberHandling = MissingMemberHandling.Ignore
                });

                var identity = new ClaimsIdentity(
                    new[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, jwt.Subject, xmlString, jwt.Issuer),
                        new Claim(ClaimTypes.Name, jwt.Subject, xmlString, jwt.Issuer),
                        new Claim(ClaimTypes.UserData, claims, xmlString, jwt.Issuer)
                    },
                    jwt.Issuer,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                context.User.AddIdentity(identity);

I’ve created a new class – JsonWebToken.cs – to hold the claim:

using Newtonsoft.Json;

namespace aurelia_2.Middleware
{
    public class JsonWebToken
    {
        [JsonProperty("iss")]
        public string Issuer { get; set; }

        [JsonProperty("sub")]
        public string Subject { get; set; }

        [JsonProperty("aud")]
        public string Audience { get; set; }

        [JsonProperty("exp")]
        public long Expiry { get; set; }

        [JsonProperty("iat")]
        public long IssuedAt { get; set; }
    }
}

Now my issuer is my Auth0 domain instead of the custom issuer string and my name (which I will use as a unique identifier for the user) is the JWT subject field.

Wrap Up

That’s it for my investigation into authentication with ASP.NET MVC6 WebAPI. To re-cap:

  1. I followed the Aurelia tutorial, but adjusted for TypeScript and ASP.NET
  2. I added an Auth0 pop-up to authenticate using a service
  3. I used that authentication to affect routing on the client side
  4. I added the authorization JWT to a WebAPI request
  5. I decoded the JWT in a Controller
  6. I made the JWT an authorization middleware (this article)

That’s a lot of code and I hope you enjoy it. The code is on my GitHub Repository.

Calling an ASP.NET WebAPI From Aurelia

In my last article, I promised I would deal with authentication of an ASP.NET WebAPI. Well, to do that, I need a WebAPI and I didn’t want to mix the additions because of the WebAPI with the additions because of the authentication requirements. As a result, I decided to add a page to my Aurelia app that utilized the WebAPI to return some data.

Create a WebAPI

I’m going to create a simple WebAPI for this example. When I do a GET /api/spells, it will return a simple JSON object like this: {id: 1}. It’s really the most simple WebAPI you could possibly produce.

First off, I’ve already added Microsoft.AspNet.Mvc to my project.json file. I only have to create a Controller class. That is located in Controllers/SpellsController.cs. I had to create the Controllers directory since this is my first controller.

using Microsoft.AspNet.Mvc;

namespace aurelia_2.Controllers
{
    [Route("api/[controller]")]
    public class SpellsController : Controller
    {
        [Route("")]
        public string GetAll()
        {
            return "{id:1}";
        }
    }
}

You can test this with Postman or a similar REST client. Just send a GET request for /api/spells and you will see the embedded string returned. Note that I didn’t have to provide a route map to the app.useMvc() call in Startup.cs. It happens thanks to the decorators on the class.

Creating a new View in Aurelia

Back to my Aurelia page, I wanted to create a new view called “spells”. I need two files – pages/spells.html contains my view:

<template>
    <section>
        <h2>${heading} - ${code}</h2>
        <div id="data">
            ${data}
        </div>
    </section>
</template>

The heading, code and data variables are bound to the class – pages/spells.ts contains the definition:

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';

export class Spells {
    public heading: string = 'Spells';
    public data: string = '';
    public code: string = '';
    private loading: boolean = false;
    private http: HttpClient = null;

    constructor() {
        var auth_token = localStorage.getItem("auth_token");
        if (auth_token != null) {
            this.http = new HttpClient().configure(x => {
                x.withBaseUrl(window.location.origin);
                x.withHeader("Authorization", "Bearer " + localStorage.getItem("auth_token"));
                x.withHeader("Accept", "application/json");
            });
        } else {
            this.http = new HttpClient().configure(x => {
                x.withBaseUrl(window.location.origin);
            });
        }
    }

    activate() {
        this.loading = true;
        return this.http.get("/api/Spells").then(response => {
            this.data = response.content;
            this.code = response.statusCode.toString();
            this.loading = false;
        });
    }


    canDeactivate() {
        if (this.loading) {
            return confirm("Still loading - are you sure?");
        }
        return true;
    }
}

The constructor should have a little explanation. Firstly, I pull the auth_token. If I’m authenticated, then I will create a new HttpClient object that contains the authorization. If the user is not signed in, then I create a new HttpClient() object without the authorization. That way, the usage of the WebAPI follows the status of the user. Signed in – send the authorization. Not signed in – don’t. I’d probably abstract this (and all the other authentication information) into it’s own class in a real application.

If you remember the flickr page from the Aurelia tutorial, you will note that the activate() methods and canDeactivate() methods (which are part of the page lifecycle that Aurelia provides). When I get a response from the server, I set the data and code and the values will get automatically reflected in the view.

Wire in the new View

Before I can use the view I’ve just created, I need to create a route for it. That is done within the configureRouter() method in app.ts:

        config.map([
            { route: 'welcome', name: 'welcome', moduleId: './pages/welcome', nav: true, title: 'Welcome' },
            { route: 'flickr', name: 'flickr', moduleId: './pages/flickr', nav: AuthorizeStep.isLoggedIn(), auth: true, title: 'Flickr' },
            { route: 'spells', name: 'spells', moduleId: './pages/spells', nav: true, title: 'Spells' },
            { route: '', redirect: 'welcome' },
        ]);

Don’t forget to clear your cache before reloading the page. I found that the browser hung on to this javascript file until I did.

Running the project will provide the appropriate response. You will see a Spells link on the top bar. Clicking on the Spells link will do an XHR request to the backend, which will then fill in the data for you. If you are viewing the page in Chrome, you can open up the Developer Tools and click on Network. Reload the page and check out the XHR request for /api/Spells – you will note the Authorization header if you are signed in.

This means I am now all ready for dealing with authentication. I have a page that should send the appropriate authentication when signed in. However, my backend is not configured to handle that authentication yet – in fact, it simply ignores it.

You can get this code from my GitHub Repository.