Securing Umbraco Web APIs using JSON Web Tokens

Hello all,
First off a very happy new year to you all. I hope you had a good time off over the festive period and relaxed.

Over this festive period in between our baby girl arriving during late night feeds and insomnia kicking in, I managed to find a little time to polish off my new pet project for the wonderful Umbraco CMS. So I herby introduce you to UmbracoAuthTokens!

What is Umbraco Auth Tokens?

Umbraco Auth Tokens is a project that I have built that allows you to secure Umbraco WebAPI Controllers using a token based authentication using JSON Web Tokens aka JWT; pronounced jot. This is ideal for securing WebAPIs that require using a backoffice Umbraco user.

For example you may want to securely from a third party client be it a mobile application or similar create a new page or any other action that a backofficer Umbraco user may do.

What are JWTs?

They are an auth token that allows you to send a piece of JSON encoded as a token and are the more modern approach to deal with auth in applications especially as we build applications across different devices. The videos below will do a lot better trying to explain it than I can do.

Continue reading “Securing Umbraco Web APIs using JSON Web Tokens”

Advertisements

We are Umbraco Craftsmen

We are Umbraco Craftsmen

I recently gave a talk at the annual Umbraco Developer Conference CodeGarden, about ‘The Analytics for Umbraco Story’. In this talk I discussed that we are all digital craftsmen.

Continue reading “We are Umbraco Craftsmen”

Visual Studio Extensions for Umbraco

Hello all,
I haven’t blogged for a little while, as I have been busy with my new pet project uHangout. If you haven’t checked it out yet I highly recommend you do, as it s a weekly Google Hangout that I record and publish on YouTube with guests from the Umbraco community demoing implementations, snippets, packages or just general interviews like I did with founder Niels Hartvig & Per Ploug

So my next little lunchtime hacks has been involved in working with extending Visual Studio to make our life’s easier when working with Umbraco. After recently coming across the project SideWaffle from Sayed Hashimi and Mads Kristensen from Microsoft, I was inspired by how they have added new file templates such as an AngularJS Controller and others.

So with this idea I approached Sayed for some advice on how I can create Umbraco file templates in the same way. I was given some great pointers and I am now able to present to you the

Umbraco Community – Visual Studio Project Item Templates package for Visual Studio

You can download the extension directly inside Visual Studio from the extensions section or on the Visual Studio Gallery website.

If you are intrigued on how it all works then the full source code is available on GitHub for you to look through as well.

But it doesn’t stop there!

As I created another Visual Studio package that adds a new project template to Visual Studio. So with one click you can do File -> New Project and select the new Umbraco project template. This will install and setup Umbraco for you by fetching the latest version of Umbraco from NuGet.

Now you will be able to impress your boss as you install & setup Umbraco so quickly.
Like before this extension can be found when searching inside Visual Studio for extensions and the gallery website but I have also put the source code of is extension on GitHub as well.

I have a few more ideas for Visual Studio Extensions to make our lives easier as Umbraco Developers, but I would love to hear what you think.

Cheers,
Warren 🙂

Diagnostics for Umbraco

Well after a short weeks holiday I have come back and released a new must have package for any Umbraco 6.1 site or newer. This handy little package is called Diagnostics and it does exactly what it says on the tin. It shows you diagnostical information about your Umbraco install.

Features

This package was a bit of an experiment for me in order to learn how to write an AngularJS application. So later on this post I will cover some of the basics of what I wrote and show you some parts of the code.

  • Umbraco Version, assembly & release notes
  • Database type & connection string
  • Server information, ASP.NET version etc…
  • Assemblies along with MD5 & SHA1 Checksums
  • List the packages installed
  • List the Umbraco backoffice users
  • List the domains in use for the site
  • List all the folders and their current permissions applied to them
  • List all the Umbraco events and what is attached to those events
  • List the MVC Routes used in the site
  • List all the Trees used within the Umbraco backoffice

Let’s see it in action

Please note this video is ever so slightly out of date and the UI has been given a little bit love rather than messy UL list’s

http://screenr.com/0iRH

Download it

You can download the Diagnostics package from the Our Umbraco project page and the source code is publicly available on GitHub where you can view the source and log any issues along with any feature requests.

Show me the code!

OK so this was my first experiment into the world of AngularJS and I wanted to build a small app using it, as the new Umbraco user interface is getting overhauled in version 7 aka Belle and will be using AngularJS as well. So any head start on this would be highly beneficial.

Firstly I looked at many videos and resources before diving in. But the video I highly recommend you watch is this one from Dan Wahlin

Now you have watched that I can go over some parts of the code.

First let’s start with the index.html page found in /App_Plugins/Diagnostics.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Umbraco Diagnostics</title>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css">
</head>
<body ng-app="umbracoDiagnosticsApp">
    
    <h1>Diagnostics</h1>
    <!-- Nav -->
    <ul class="nav nav-tabs">
        <li ng-class="{active: locationUrl == '/'}">
            <a href="#/">General</a>
        </li>
        <li ng-class="{active: locationUrl == '/packages'}">
            <a href="#/packages">Packages</a>
        </li>
        <li ng-class="{active: locationUrl == '/users'}">
            <a href="#/users">Users</a>
        </li>
        <li ng-class="{active: locationUrl == '/domains'}">
            <a href="#/domains">Domains</a>
        </li>
        <li ng-class="{active: locationUrl == '/assemblies'}">
            <a href="#/assemblies">Assemblies</a>
        </li>
        <li ng-class="{active: locationUrl == '/permissions'}">
            <a href="#/permissions">Permissions</a>
        </li>
        <li ng-class="{active: locationUrl == '/events'}">
            <a href="#/events">Events</a>
        </li>
        <li ng-class="{active: locationUrl == '/routes'}">
            <a href="#/routes">MVC Routes</a>
        </li>
        <li ng-class="{active: locationUrl == '/trees'}">
            <a href="#/trees">Trees</a>
        </li>
    </ul>

    <!-- Placeholder for views -->
    <div ng-view=""></div>
    
    <!-- JS -->
    <script type="text/javascript" src="scripts/angular1.0.7.min.js"></script>
    <script type="text/javascript" src="scripts/app.js"></script>

    <!-- Latest compiled and minified JavaScript -->
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
</body>
</html>

The things to note is the ng-app attribute on the body tag, the ng-class attributes on the LI elements and the ng-view on the div.

I will cover what these items do a bit later on.

Next we need to take a look at the app.js file in /App_plugins/Diagnositcs/scritps/app.js

var umbracoDiagnosticsApp = angular.module('umbracoDiagnosticsApp', []);

umbracoDiagnosticsApp.config(function($routeProvider) {
    $routeProvider
        .when('/',
            {
                controller: 'GeneralController',
                templateUrl: 'partials/general.html'
            })
        .when('/packages',
            {
                controller: 'PackagesController',
                templateUrl: 'partials/packages.html'
            })        
        .otherwise({ redirectTo: '/' });
});


/*
=====================================
CONTROLLERS
=====================================
*/

//General Controller
umbracoDiagnosticsApp.controller('GeneralController', function ($scope, $http, $rootScope, $location) {
    $http.get('/Umbraco/Api/DiagnosticsApi/GetVersion').success(function (data) {
        $scope.version = data;
    });

    $http.get('/Umbraco/Api/DiagnosticsApi/GetVersionAssembly').success(function (data) {
        $scope.assembly = data;
    });
    
    $http.get('/Umbraco/Api/DiagnosticsApi/GetVersionComment').success(function (data) {
        $scope.comment = data;
    });
    
    $http.get('/Umbraco/Api/DiagnosticsApi/GetServerInfo').success(function (data) {
        $scope.server = data;
    });
    
    $http.get('/Umbraco/Api/DiagnosticsApi/GetDBInfo').success(function (data) {
        $scope.db = data;
    });
    
    //Pass location url value into an item on our scope object
    $rootScope.locationUrl = $location.$$url;
});

//Packages Controller
umbracoDiagnosticsApp.controller('PackagesController', function ($scope, $http, $rootScope, $location) {
    $http.get('/Umbraco/Api/DiagnosticsApi/GetPackages').success(function (data) {
        $scope.packages = data;
    });
    
    //Pass location url value into an item on our scope object
    $rootScope.locationUrl = $location.$$url;
});

The very first line in this app.js defines our AngularJS module and in this case it’s called umbracoDiagnosticsApp and this needs to be in the ng-app attribute in the HTML document as shown above.

The next part of this file is to wire up the URL routes, so when the link/URL changes we can load in a different view and controller into our div with the attribute of ng-view.

So when we click on the different tabs such as Packages, it loads the URL #/packages and then maps the view /partials/packages.html and to use the packages controller.

In this controller for packages we do a HTTP WebAPI call to /Umbraco/Api/DiagnosticsApi/GetPackages fetch some JSON and then we store the results of the JSON into an object called packages which we then use in our view.

So lets take a look at the partial view for packages to see how we display the package information.

<table class="table table-striped table-hover">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Version</th>
            <th>Author</th>
            <th>Has Update?</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="package in packages">
            <td>{{ package.Id }}</td>
            <td>{{ package.Name }}</td>
            <td>{{ package.Version }}</td>
            <td>{{ package.Author }}</td>
            <td>{{ package.HasUpdate }}</td>
        </tr>
    </tbody>
</table>

So we use mustache in our partial view to output the properties stored in our packages JSON we received from our WebAPI call and with the ng-repeat attribute we can easily loop over each item in the collection and output the properties stored in the JSON.

So the final piece of the puzzle is to have a WebAPI setup in Umbraco to get our information back as JSON.

using umbraco.cms.businesslogic.web;
using Umbraco.Core.Configuration;
using umbraco.interfaces;
using Umbraco.Web.WebApi;
using umbraco.cms.presentation.Trees;
using Package = umbraco.cms.businesslogic.packager.repositories.Package;

namespace CWS.UmbracoDiagnostics.Web.Controllers
{
    public class DiagnosticsAPIController : UmbracoAuthorizedApiController
    {

        public List<PackageInstance> GetPackages()
        {
            var allPackages = new List<PackageInstance>();

            //Get packages
            var packages = InstalledPackage.GetAllInstalledPackages();

            //loop over them
            foreach (var item in packages)
            {
                allPackages.Add(item.Data);
            }

            //Return the list
            return allPackages;
        }        
    }
}

So in this WebAPI controller class I inherit from UmbracoAuthorizedApiController which only allows these requests to be made to the API if you are logged into the Umbraco backoffice to ensure this information is not publicly available.

So in a nutshell that is all the components that makes up this AngularJS Umbraco Diagnostics application.

Any questions or improvements to this then please let me know.

Thanks,
Warren

Highlight Errors in CodeMirror

Hello all,
With the release of Optimus for Umbraco that me & Tim Geyssens have built that allows you to create bundles and write Sass, Less, CoffeeScript & TypeScript files directly inside Umbraco.

We wanted a way to highlight any compiling errors with your code that you write, by highlighting the line number in the editor of the Umbraco back office.

The code editor inside Umbraco, uses the highly popular HTML & JavaScript code editor CodeMirror. My goal was to highlight the exact line number in the editor so we can visually highlight to the user where in their code that is the problem.

So I will take you through the small code snippet that was used to achieve this:

In the FileEditor.aspx page that we have I wrote the following JavaScript function

    function highlightLine(lineNumber) {

        //Line number is zero based index
        var actualLineNumber = lineNumber - 1;

        //Select editor loaded in the DOM
        var myEditor = $("#body_EditorSource .CodeMirror");

        //Write the item to the console window, for debugging
        console.log(myEditor);

        //Select the first item (zero index) just incase more than one found & get the CodeMirror JS object
        var codeMirrorEditor = myEditor[0].CodeMirror;

        //Write the item to the console window, for debugging
        console.log(myEditor[0].CodeMirror);

        //Set line CSS class to the line number & affecting the background of the line with the css class of line-error
        codeMirrorEditor.setLineClass(actualLineNumber, 'background', 'line-error');
    }

In addition to this I need a small chunk of CSS in order to style the error line in red for it to be easily noticed.

<style>
        .line-error {
            background: #FBC2C4 !important;
            color: #8a1f11 !important;
        }

</style>

The final thing that needs for this all to come together and work, is that when the save button is hit on our custom code editor page, that we check for any errors from the transformers such as Sass & CoffeeScript for example. Parse the line number and pass that to our Javascript function highlightLine().

        private bool SaveConfigFile(string filename, string contents)
        {
           //This gets the filename of the Sass, Less, CoffeeScript or TypeScript file
            var path = Request.QueryString["path"] + filename;

            //This gets the full path to the file (Server MapPath'd)
            var fullPath = Server.MapPath(Request.QueryString["path"]) + filename;

            //Open up the file on disk
            using (var text = File.CreateText(fullPath))
            {
                //Save the file contents
                text.Write(contents);

                //Close the text reader, as we are done with it
                text.Close();

                //Check the translation for errors
                var errors = transCore.ValidateTranslation(path);

                //If no errors then...
                if (errors == null || !errors.Any())
                {
                    //Save the translation to disk
                    transCore.SaveTranslation(path);
                    return true;
                }
                else
                {
                    //Get the first exception message out of the collection
                    var exceptionMessage = errors.First().Message;

                    //Set the panel on the page - it's an error type & show the exception message
                    Feedback.type = Feedback.feedbacktype.error;
                    Feedback.Text = exceptionMessage;
                    Feedback.Visible = true;

                    //Get Line number from the exception message - presumes messages always ends with
                    //Line number: 3
                    var lineNumber = exceptionMessage.Split(' ').Last().Replace("\r", "").Replace("\n", "");
                    int.TryParse(lineNumber, out ErrorLineNumber);

                    return false;
                }
            }

So that’s all the parts of our code that enables us to highlight the line number in the CodeMirror editor.

There is plenty more that could be done with the editor, as there are many options available to us when we have the CodeMirror object selected in JavaScript. So let your imagination go wild and start playing around with the code editor inside Umbraco.

Any questions please leave them in the comments.

Thanks,
Warren 🙂

Transformers! Robots in Disguise

Transformers! Robots in Disguise

Transformers, robots in disguise! Was part of the classic 80’s cartoon Transformers theme tune and has been inspiration for Tim Geyssens and mine latest Umbraco package, aptly named Optimus. After Optimus Prime, the lead transformers of the Autobots.

So what is Optimus and why did you call it that? Well read on to find out!
Continue reading “Transformers! Robots in Disguise”