Decrypting JSON Web Encrypted tokens in PCL

This week I worked on a feature for a Xamarin app I’m building that gave me quite some headaches because it involved a good amount of yak shaving to get it working correctly. My main reason for blogging this is for my own reference in the future, but maybe it can help someone else too 🙂

yak shaving
Yak shaving, gotta love it…

Our team is building a cross platform Xamarin app that has a good amount of shared code in an MVVM architecture. Most of the app is implemented in PCL libraries with a front end project per platform.

For communicating with a backend API, the app requires a token obtained from an Identity Provider. In addition to the API access token, we’re also getting an OpenId token that is crucial for the app. Using Xamarin.Auth for example, it’s pretty easy to setup an OAuth flow that lets the user login and the app obtain that token.

So far so good.

There’s a lot to be said about which OAuth flow is suitable in which scenario. For us, embedding a client secret in the app was a no go, since this can’t be kept secret if it’s embedded in the source code of the app (reverse engineering!). We chose a PCKE approach. Without going into too much detail around the flow, I want to focus on one aspect: securing the OpenID token. This blogpost is mostly about what I learned about token encryption and decryption.

207h

Our requirement was to have asymmetric encryption in place, where the app provides a public key to the server, which it uses to encrypt the JWT. The app can then decrypt the data using its private key, so we could mitigate a token interception attack. The public key was to be transferred in an X509 certificate (PEM encoded). The idea was to have the app generate a private/public keypair on-the-fly as we don’t want to hard code a private key into the app. That would lead us to the same situation as the hard coded Client Secret. All we want is to make sure that the requesting app is the only one able to decrypt the token it requested.

There’s a nice standard for encrypting tokens using a variety of algorithms: JWE – JSON Web Encryption. The original token is in a JSON structure, encrypted and packaged into a standardized format. In our case, these were the specs:

Algorithm: RSA_OAEP – RSAES using Optimal Asymmetric Encryption Padding (OAEP) (RFC 3447), with the default parameters specified by RFC 3447 in section A.2.1

Encryption method:  A256GCM – AES in Galois/Counter Mode (GCM) (NIST.800-38D) using a 256-bit key

Basically what happens is: the token payload is encrypted using a random Content Encryption Key (CEK) provided by the server. This is an authenticated encryption mode, where data is added to prove authenticity. In addition to the key, an Initialization Vector (IV) is added, and also an Authentication Tag (authTag) and Additional Authenticated Data, basically consisting of a Base64 representation of the JWE header. All this together provides a symmetric encryption through which we can decrypt the token. This is the A256CGM – AES step.

All the information I mentioned – the CEK, IV, cipherText (the encrypted token), AAD and authTag – are present in the JWE package. To add the final layer of security, the CEK has to be encrypted, otherwise anyone would be able to read the token. This is the RSA_OAEP – RSAES step mentioned earlier. In plain English, the CEK is encrypted using asymmetric encryption. The server uses the app’s public key for this, obtained from the X509 certificate in the request.

So the way back to obtain the token plain text is to decrypt the CEK using the private key, and then decrypt the token payload using the CEK together with the IV, AAD and authTag, as illustrated in the diagram below:

jwe-decryption

That looks pretty daunting, but luckily there are libraries that help us handle this scenario, or the many other combinations of algorithms and encodings. One popular example is the JOSE-JWT library for .NET. You can feed it the complete JWE package and the CEK decryption key, and it does all the heavy lifting. JOSE-JWT can also handle our scenario, with our combination of algorithms and encodings.

Here’s the catch…

This won’t fly in a PCL. JOSE-JWT is built on System.Security.Cryptography, which isn’t available in PCL code. There have been some attempts to make JOSE-JWT available for Xamarin, but this won’t work fully cross platform. So ideally, we’d want a library that solves this using PCL compatible API’s. And sadly, there is no JOSE-JWT implementation available for PCL yet.

281H_banner.png
Now what?!

JWE just uses standard encryption algorithms, so it should be possible to implement these on top of a crypto API that is available cross platform (in PCL). I have tried two options:

  • PCLCrypto: this library mimics the WinRTCrypto API’s but relies on native, platform specific crypto-engines to perform the encryption. This results in the fastest encryption engine but is limited in terms of supported scenario’s or algorithms.
  • BouncyCastle-PCL: a cross platform crypto library that supports all sorts of cryptographic algorithms.

Since PCLCrypto mimics the WinRTCrypto API, it seemed pretty easy to implement our JOSE-JWT port on top of PCLCrypto, by stealing borrowing from the experimental JOSE-RT port. (Thanks Dmitriy Vsekhvalnov for the tip!) And indeed, if you look at the AesGcmEncryptor class, it looks rather straight forward. Alas, it turns out our GCM authenticated mode isn’t supported by PCLCrypto. It threw a NotSupportedException at me.

So the other option was to use BouncyCastle-PCL. We ended up with a solution that does the following:

  • Generation of the public/private keypair
  • Generation of the X509 certificate containing the public key
  • Unpacking the JWE package
  • Decrypting (or unwrapping) the CEK using the private key
  • Decrypting the token payload

Mind you, I only had to support our specific scenario, but it’s a small step towards a full JOSE-PCL implementation. Maybe someday I’ll make an attempt 🙂

Without further ado, here is the code I ended up with:

using System;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Operators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.IO.Pem;
using Org.BouncyCastle.X509;
using System.Linq;

namespace JoseJWE
{
	public class CryptoService
	{
		public AsymmetricCipherKeyPair GenerateKeyPair()
		{
			var random = new SecureRandom();
			var keyGenerationParameters = new KeyGenerationParameters(random, 1024);
			var keyPairGenerator = new RsaKeyPairGenerator();
			keyPairGenerator.Init(keyGenerationParameters);
			var keyPair = keyPairGenerator.GenerateKeyPair();
			return keyPair;
		}

		public string GeneratePemEncodedCertificate(AsymmetricCipherKeyPair keyPair)
		{
				var random = new SecureRandom();
				var signatureFactory = new Asn1SignatureFactory("SHA256WithRSA", keyPair.Private, random);

				var gen = new X509V3CertificateGenerator();
				gen.SetPublicKey(keyPair.Public);

				BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
				gen.SetSerialNumber(serialNumber);

				var x509Name = new X509Name("CN=MyCertificate,O=RoyCornelissen,OU=CryptoService");
				gen.SetIssuerDN(x509Name);
				gen.SetSubjectDN(x509Name);

				gen.SetNotBefore(DateTime.UtcNow.AddHours(-1));
				gen.SetNotAfter(DateTime.UtcNow.AddMonths(1));

				var x509 = gen.Generate(signatureFactory);
				x509.CheckValidity(DateTime.UtcNow);
				x509.Verify(keyPair.Public);

				using (var stringWriter = new StringWriter())
				{
					var writer = new PemWriter(stringWriter);
					var pog = new PemObject("CERTIFICATE", x509.GetEncoded());
					writer.WriteObject(pog);
					return stringWriter.ToString();
				}
		}

		public string DecodeJwt(string tokenData, AsymmetricKeyParameter privateKey)
		{
			var token = Parse(tokenData);
			return DecodeAndDecrypt(token, privateKey);
		}

		private string DecodeAndDecrypt(byte[][] parts, AsymmetricKeyParameter key)
		{
			byte[] header = parts[0];
			byte[] encryptedCek = parts[1];
			byte[] iv = parts[2];
			byte[] cipherText = parts[3];
			byte[] authTag = parts[4];

			var cek = Unwrap(encryptedCek, key);
			var aad = Encoding.UTF8.GetBytes(Serialize(header));

			return Decrypt(cek, iv, aad, cipherText, authTag);
		}

		private string Serialize(params byte[][] parts)
		{
			var builder = new StringBuilder();

			foreach (var part in parts)
			{
				builder.Append(Base64UrlEncode(part)).Append(".");
			}

			builder.Remove(builder.Length - 1, 1);

			return builder.ToString();
		}

		private byte[][] Parse(string token)
		{
			string[] parts = token.Split('.');

			var result = new byte[parts.Length][];

			for (int i = 0; i < parts.Length; i++)
			{
				result[i] = Base64UrlDecode(parts[i]);
			}

			return result;
		}

		private byte[] Unwrap(byte[] encryptedCek, AsymmetricKeyParameter key)
		{
			var decryptEngine = new OaepEncoding(new RsaEngine());
			decryptEngine.Init(false, key);
			var deciphered = decryptEngine.ProcessBlock(encryptedCek, 0, encryptedCek.Length);
			return deciphered;
		}

		//Preconfigured Encryption Parameters
		private static readonly int MacBitSize = 128;

		/// <summary>
		/// Performs AES decryption in GCM chaining mode over cipher text
		/// </summary>
		/// <param name="cek">aes key</param>
		/// <param name="iv">initialization vector</param>
		/// <param name="aad">additional authn data</param>
		/// <param name="cipherText">cipher text message to be decrypted</param>
		/// <param name="authTag">authentication tag</param>
		/// <returns>decrypted plain text messages</returns>
		private string Decrypt(byte[] cek, byte[] iv, byte[] aad, byte[] cipherText, byte[] authTag)
		{
				var keyParameter = new KeyParameter(cek);
				var gcmParameters = new AeadParameters(
					keyParameter,
					MacBitSize,
					iv);

				var gcmMode = new GcmBlockCipher(new AesFastEngine());
				gcmMode.Init(false, gcmParameters);
				gcmMode.ProcessAadBytes(aad, 0, aad.Length);

				var cipherBuffer = cipherText.Concat(authTag).ToArray();
				var plainBytes = new byte[gcmMode.GetOutputSize(cipherBuffer.Length)];
				var res = gcmMode.ProcessBytes(cipherBuffer, 0, cipherBuffer.Length, plainBytes, 0);
				gcmMode.DoFinal(plainBytes, res);

				var plain = Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length);
				return plain;
		}

		// from JWT spec
		public byte[] FromBase64Url(string base64Url)
		{
			string padded = base64Url.Length % 4 == 0
				? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
			string base64 = padded.Replace("_", "/")
									.Replace("-", "+");
			return Convert.FromBase64String(base64);
		}

		// from JWT spec
		public string Base64UrlEncode(byte[] input)
		{
			var output = Convert.ToBase64String(input);
			output = output.Split('=')[0]; // Remove any trailing '='s
			output = output.Replace('+', '-'); // 62nd char of encoding
			output = output.Replace('/', '_'); // 63rd char of encoding
			return output;
		}

		// from JWT spec
		private byte[] Base64UrlDecode(string input)
		{
			var output = input;
			output = output.Replace('-', '+'); // 62nd char of encoding
			output = output.Replace('_', '/'); // 63rd char of encoding
			switch (output.Length % 4) // Pad with trailing '='s
			{
				case 0: break; // No pad chars in this case
				case 1: output += "==="; break; // Three pad chars
				case 2: output += "=="; break; // Two pad chars
				case 3: output += "="; break; // One pad char
				default: throw new Exception("Illegal base64url string!");
			}
			var converted = Convert.FromBase64String(output); // Standard base64 decoder
			return converted;
		}
	}
}

Its usage is demonstrated by the following unit tests:


<pre>using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Jose;
using NUnit.Framework;
using Org.BouncyCastle.Crypto.Parameters;

namespace JoseJWE.Tests
{
	[TestFixture]
	public class CryptoServiceTests
	{
		private const string TokenPlainText = "{\"sub\":\"roycornelissen\",\"aud\":\"sample app\",\"nbf\":136424444,\"iss\":\"https://api.someorganization.com\",\"preferred_username\":\"Roy Cornelissen\",\"exp\":1364293137,\"given_name\":\"Roy\",\"iat\":13642555,\"family_name\":\"Cornelissen\",\"preferred_language\":\"nl-NL\"}";

		[Test]
		public void GenerateCertificate_Generates_Valid_X509Certificate()
		{
			var g = new CryptoService();
			var keyPair = g.GenerateKeyPair();

			var pemEncodedCertificate = g.GeneratePemEncodedCertificate(keyPair).ToString();

			var p = new Org.BouncyCastle.X509.X509CertificateParser();
			var certDecoded = p.ReadCertificate(Encoding.UTF8.GetBytes(pemEncodedCertificate));

			certDecoded.Should().NotBeNull();
			certDecoded.NotBefore.Should().BeBefore(DateTime.UtcNow);
			certDecoded.NotAfter.Should().BeAfter(DateTime.UtcNow);
		}

		[Test]
		public void Certificate_Used_For_JWT_Encryption_JWE_Can_Be_Decrypted()
		{
			var g = new CryptoService();
			var keypair = g.GenerateKeyPair();

			var cert = g.GeneratePemEncodedCertificate(keypair);
			var base64Certificate = g.Base64UrlEncode(Encoding.UTF8.GetBytes(cert));

			// try to perform local encryption and decryption for reference
			var p = new Org.BouncyCastle.X509.X509CertificateParser();
			var certDecoded = p.ReadCertificate(g.FromBase64Url(base64Certificate));

      // use 3rd party library JOSE-JWT to encode the JWT (only works in .NET, not from PCL!)
			var publicRsaKey = ToRSA((RsaKeyParameters)certDecoded.GetPublicKey());
			var encrypted = JWT.Encode(TokenPlainText, publicRsaKey, JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM);

			// now attempt to decode it using our own cryptoService
			var plainText = g.DecodeJwt(encrypted, keypair.Private);
			plainText.Should().Be(TokenPlainText);
		}
    
    public static RSA ToRSA(RsaKeyParameters rsaKey)
    {
        RSAParameters rp = ToRSAParameters(rsaKey);
        RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider();
        rsaCsp.ImportParameters(rp);
        return rsaCsp;
    }

    private static RSAParameters ToRSAParameters(RsaKeyParameters rsaKey)
    {
        RSAParameters rp = new RSAParameters();
        rp.Modulus = rsaKey.Modulus.ToByteArrayUnsigned();
        if (rsaKey.IsPrivate)
            rp.D = rsaKey.Exponent.ToByteArrayUnsigned();
        else
            rp.Exponent = rsaKey.Exponent.ToByteArrayUnsigned();
        return rp;
    }
	}
}</pre>

The entire Gist is here on GitHub.

Ceci n’est pas une app

LevelUpMobile_logoRGBCall to action: join us at LevelUp Mobile on September 22nd in Leusden for a FREE inspirational evening on the future of Mobility and Devices.

 

The mobile platform war has been raging for almost ten years now. For now, it seems that Google (Android) and Apple (iOS) have won. (link) Microsoft, though still pushing Windows 10 for mobile as well, has accepted this and started providing high quality mobile apps for both Android and iOS.

Apple and Google have invested a lot in making their platforms richer and richer to attract and retain users. Apple’s advantage of 100% vertical integration of software and hardware has allowed them to create experiences like Apple Pay, 3D-Touch and Touch-ID that are very appealing to users and developers alike. At the same time, both Apple and Google have been putting features into the OS and stock apps that are competing with 3rd party offerings in the App Store. Furthermore, users have come to expect the same experience they get from their OS from 3rd party apps. Though some platform features might seem alike between iOS, Android and Windows, the way they are implemented can vastly differ and require access to core platform API’s.

As a strong proponent of Xamarin, I’ve been working in the world of cross platform mobile app development for almost 6 years now. The reason we chose to go with Xamarin was – first of all – of course the ability to share code amongst platforms, but – equally important – full access to the native platform API’s and the ability to create 100% native experiences. Given the trend of ever innovating mobile platforms, this puts us at a huge advantage over cross platform solutions that go for the lowest common denominator, both in UI (the same UI across all platforms) and UX (most of the time just the common superficial feature set across platforms).

With iOS 10, Apple is showing us a trend where apps can be integrated even deeper in the core OS experience. Of course we already had widgets in Android, but what to think about interactive widgets in iOS’s Today view, enriched with Siri’s AI capabilities? Interactive notifications are becoming more popular. Where a notification used to be a way to alert the user and allow them to open the accompanying app by tapping on it, notifications are becoming a User Interface by themselves, allowing the user to deal with the app’s functionality right from the lock screen.

ios-10-interactive-notifications
Deal with a notification right away from the Home screen. No need to open the app!
The boundaries of apps are blurring even more with advanced features like 3D-touch on the Home screen, and the ability to interact with apps from the Siri screen:

iOS-10-Control-Center-3D-Touch-iPhone-screenshot-001
Direct access to an app’s features through 3D-Touch. No need to open the app!

open_app_in_siri
Siri knows how to invoke your app and show it as a widget right inside its own interface. No need to open the app!

apps_in_imessage
iMessage can invoke your app right from its own interface. No need to open your app!
These are all iOS examples, by the way, but similar features can be found in Android and Windows 10, with its Live Tiles, Cortana integration, etcetera.

In general, user interaction with their mobile devices is becoming more and more streamlined, and to stay ahead as developers, we need to start thinking about these micro-interactions, these Mobile Moments, and offer the most efficient experience with our apps.

Mobile is not a neutral platform (link). The philosophy of web applications (built for browsers, available everywhere, with a consistent user experience everywhere) doesn’t apply here. We don’t build for the web, we build for the OS. Yay for native development! 🙂

spoon-boy
There is no spoon.
If we follow this train of thought, it leads us to an existential question: is there actually an app?

I would argue: not anymore – at least not in the traditional sense where we have an icon sitting on the home screen that launches into an application that comes into the foreground and occupies the whole screen. It seems like the days of the mobile “app” are numbered and we have to start thinking about apps as a set of autonomous micro-interactions that work together with the OS and/or other apps.

Luckily for us, as developers, there are plenty of new API’s and frameworks that help us build these interactions and I think it will only become more exciting from a technical perspective to build mobile experiences.

LevelUpMobile_logoRGB

On September 22nd, I’m joining Brechtje de Leij (mobile strategist and expert), Jorn de Vries of Flitsmeister fame, Johan Gorter & Rick Hoving from AFAS Software and the ever brilliant Laurent Bugnion to speak at a one-off inspiring event about the future of Mobile and Devices: LevelUp Mobile. Together with my colleague Geert, our talk is going to be about the exact topic of this blogpost and we’ll show some real life examples of how to implement these Mobile Moments using Xamarin.

If you have not registered yet, you can do it here: http://www.levelupmobile.nl! It’s free and it’s going to be fun!

To get more inspired, read Laurent’s teaser blog post about his upcoming talk: A world of devices.

An NServiceBus backplane for SignalR

[UPDATE December 6th 2015: With thanks to Ramon Smits of Particular, the sample repo has now been upgraded to the latest stable versions of both NServiceBus and SignalR. Thanks Ramon!]

On March 7th 2013 I did a presentation on Microsoft Techdays NL 2013 about SignalR. This is a great framework for real time messaging in websites and other .NET clients. It also works great on mobile devices. Check out my slides in my previous post here.

In this presentation, I used a Production Monitor application that runs NServiceBus in the back end to push events to our SignalR gateway. Schematically, this looks like this:

Production Monitor

This Production Monitor gathers info from our production application at De Vries Workforce Management, a SaaS workforce planning platform for large retail organizations. Besides technical data (are our databases up?), we also gather functional data (did all shops deliver turnover data in time, did all clock times come in?).

Of course there are all kinds of monitoring applications available in the market, so why build it ourselves? First of all, our application back end is comprised of NServiceBus services, publishing all kinds of events to form our business process. By running our monitoring application as an NServiceBus service, it can also listen to those events and do its checks accordingly. The second reason for me as an architect was that this case serves as a proof of concept and exploration on how NServiceBus combines with SignalR to provide real time communication to front ends. Something we’re contemplating on putting in our application as well in due time.

Scaling out SignalR with NServiceBus
The diagram above shows how NServiceBus publishes to a SignalR Gateway, who in turn sends the information to clients connected over the web. I’ll do a separate blogpost on that later. I did a presentation on this with my lead dev and partner in crime Mark Taling at the Dutch SDN Event on March 18th in Zeist. Here are our slides from that session:

Playing with SignalR and NServiceBus together made me think about other scenario’s as well. One of the aspects that has been very nicely solved in SignalR is its scale-out scenario. Consider the following setup:

SignalR-Backplane

In a web farm that uses three servers running a SignalR gateway, with a load balancer in front, messages from one client connected to Server A, won’t be delivered to other clients what were routed to a different web server automatically. Server B wouldn’t know about messages sent through Server A without some extra help. For this, SignalR uses a so called “backplane”. Now, the backplane in SignalR is pluggable. Microsoft offers three possible backplanes out of the box: Redis, SqlServer and ServiceBus (built on the Azure/Windows ServiceBus).

Just for fun, I decided to build such a backplane using NServiceBus. You can find it here on GitHub.

Building a backplane for SignalR is not so difficult. Basically, you’ll need three main parts: the ScaleoutMessageBus, a Receiver, and the Backplane server process.

The ScaleoutMessageBus
You’ll need a class that inherits from Microsoft.AspNet.SignalR.ScaleoutMessageBus, which serves as the SignalR plugin for accessing the backplane.

public class NServiceBusMessageBus : ScaleoutMessageBus
{
internal static IBus Bus;

public NServiceBusMessageBus(IDependencyResolver resolver, IBus busInstance, ScaleoutConfiguration configuration)
: base(resolver, configuration)
{
Bus = busInstance;
Configure.Instance.Configurer.ConfigureComponent&lt;Receiver&gt;(DependencyLifecycle.InstancePerCall)
.ConfigureProperty((r) =&gt; r.SignalRMessageBus, this);

// By default, there is only 1 stream in this NServiceBus backplane, and we'll open it here
Open(0);
}

protected override Task Send(int streamIndex, IList&lt;Message&gt; messages)
{
return Task.Factory.StartNew(() =&gt;
{
ScaleoutMessage msg = new ScaleoutMessage(messages);
Bus.Send&lt;DistributeMessages&gt;(m =&gt; { m.Payload = msg.ToBytes(); m.StreamIndex = streamIndex; });
});
}

new internal void OnReceived(int streamIndex, ulong id, ScaleoutMessage messages)
{
base.OnReceived(streamIndex, id, messages);
}
}

I decided to have the constructor receive an instance of IBus from the outside. This way, the hosting application can decide for itself how NServiceBus is initialized (what transport to use, what dependency injection framework, etc.). Also, this enables the bus that might already be present in the application to be reused. Furthermore, you can specify some extra configuration for the ScaleoutMessageBus, in the form of a ScaleoutConfiguration object. For the base class, this contains only a MaxQueueLength property, but you could subclass this for your custom ScaleoutMessageBus and add more properties specific to your configuration. I decided to let the hosting application decide on the configuration, and thus pass it into the constructor as well.

SignalR will call the Send() method on this class as soon as a message needs to be sent to a group of clients. My implementation simply uses an NServiceBus command to wrap the payload, and send it via NServiceBus to the backplane server. SignalR wraps messages inside a ScaleoutMessage, which has convenient helper methods for serializing them to Byte[], so I used that to put the data on the bus.

Furthermore, I made the OnReceived method available to other classes within the same assembly via a method override. The reason for this is that the Receiver should be able to invoke OnReceived on the ScaleoutMessageBus base class, which is protected. In previous versions, I had to make sure that ScaleoutMessageBus.OnReceived could never be called in parallel, i.e. there can never be two invocations of OnReceived at the same time, so these had to be queued up. In 1.1.2, this seems to be handled by SignalR itself, so I can safely pass the call to the base class implementation.

The Receiver
The Receiver is a separate class, which is a straightforward NServiceBus message handler:

public class Receiver: IHandleMessages&lt;MessagesAvailable&gt;
{
public NServiceBusMessageBus SignalRMessageBus { get; set; }

public void Handle(MessagesAvailable message)
{
var messages = ScaleoutMessage.FromBytes(message.Payload);

if (SignalRMessageBus != null)
{
SignalRMessageBus.OnReceived(message.StreamIndex, message.PayloadId, messages);
}
}
}

The SignalRMessageBus property is wired up by NServiceBus’s dependency injection framework. As soon as the handler is instantiated, a backpointer to the ScaleoutMessageBus is put into this property.

The handler is pretty straightforward: deserializing the Payload into a ScaleoutMessage object and passing it to the OnReceived handler. The null check is done because the handler might start receiving messages left in the queue before the SignalR initialized its ScaleoutMessageBus. Yes, this means that some messages get lost, so this could be a bit more robust. Possibly by deferring the message, or using second level retries.

The Backplane server process
The backplane itself is quite simple as well… We basically need an NServiceBus host running an endpoint with the SignalRMessageDispatcher handler. This handler receives DistributeMessages commands from any SignalR Gateway, and re-publishes the payload using Bus.Publish(). Note that this handler also makes sure that the PayloadId is unique. This is required by SignalR. I just copied this behavior from the SqlServer backplane, and it seems to work fine.


public class SignalRMessageDispatcher: IHandleMessages&lt;DistributeMessages&gt;
{
private static ulong _payloadId = 0;

public IBus Bus { get; set; }

public void Handle(DistributeMessages message)
{
var evt = new MessagesAvailable()
{
Payload = message.Payload,
StreamIndex = message.StreamIndex,
PayloadId = (ulong) Interlocked.Increment(ref _payloadId)
};

Bus.Publish(evt);
}
}

You’ll just need to create an NServiceBus Endpoint (e.g. just use the generic host) and run this message handler in it. I’ve added NServiceBus.SignalR.BackplaneService assembly with an EndpointConfig to serve as a host, but you can put the handler in your own host if you will, or just tweak the NServiceBus configuration in my sample to suit your needs.

Wiring up
Now that we’ve got a ScaleoutMessageBus implementation based on NServiceBus and a backplane process, we’ll need to wire these up. First, the convention for wiring up the ScaleoutMessageBus in SignalR is to use an extension method for IDependencyResolver (the interface SignalR uses for dependency injection). This is what the UseNServiceBus() method in the DepencencyResolverExtentions class does:

public static class DependencyResolverExtensions
{
/// &lt;summary&gt;
/// Use NServiceBus backplane for SignalR.
/// &lt;/summary&gt;
/// &lt;param name="resolver"&gt;The dependency resolver.&lt;/param&gt;
/// &lt;param name="busInstance"&gt;The instance of the NServiceBus IBus instance inside the current host.&lt;/param&gt;
/// &lt;param name="configuration"&gt;Scaleout configuration parameters to be used by SignalR.&lt;/param&gt;
/// &lt;returns&gt;The dependency resolver.&lt;/returns&gt;
public static IDependencyResolver UseNServiceBus(this IDependencyResolver resolver, IBus busInstance, ScaleoutConfiguration configuration)
{
var bus = new Lazy&lt;NServiceBusMessageBus&gt;(() =&gt; new NServiceBusMessageBus(resolver, busInstance, configuration));
resolver.Register(typeof(IMessageBus), () =&gt; bus.Value);
return resolver;
}
}

You’ll use this extension method when initializing SignalR. As of SignalR 2.0.0, this is done through a Startup class:

public class Startup
{
public IBus Bus;

public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();

Bus = Configure
.With()
.DefaultBuilder()
.UseTransport&lt;Msmq&gt;()
.UseInMemoryTimeoutPersister()
.UnicastBus()
.LoadMessageHandlers()
.CreateBus()
.Start();

var config = new ScaleoutConfiguration() { MaxQueueLength = 100 }; // Or whatever you want
GlobalHost.DependencyResolver.UseNServiceBus(Bus, config);
}
}

The NServiceBusMessageBus subscribes the Receiver message handler to the MessagesAvailable event. For this, it needs to know the endpoint address of the backplane endpoint. We simply put this in the (web).config of the SignalR Gateway host:

&lt;configuration&gt;
&lt;configSections&gt;
&lt;section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" /&gt;
&lt;section name="MessageForwardingInCaseOfFaultConfig" type="NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core" /&gt;
&lt;/configSections&gt;
&lt;UnicastBusConfig&gt;
&lt;MessageEndpointMappings&gt;
&lt;!-- the endpoint on which the backplane is listening for commands --&gt;
&lt;!-- SignalR will subscribe to new messages via that endpoint --&gt;
&lt;add Messages="SignalR.NServiceBus" Endpoint="signalr.nservicebus.backplaneservice" /&gt;
&lt;/MessageEndpointMappings&gt;
&lt;/UnicastBusConfig&gt;

&lt;MessageForwardingInCaseOfFaultConfig ErrorQueue="error" /&gt;
&lt;/configuration&gt;

To test this, just create a SignalR web application that uses the backplane. Next, copy the finished application to a second directory and map it as an extra application in IIS. Be sure to give it its own input queue. Start up the backplane process and fire up both website instances. You’ll see that messages sent to/from one website instance, are also delivered to the other.

Conclusion
This was a fun exercise to show how to extend SignalR with your own backplane to support a scale out scenario. The question is how scalable the backplane process itself is. The Azure ServiceBus backplane for example can scale out itself by adding more topics. These are sharded across multiple ServiceBus instances, something not supported in my version. It all depends on how massive your messaging needs are. I have not looked into a way of increasing the topic count (i.e. the StreamCount) in this NServiceBus version for avoiding contention. I’d be interested in ways to do so.

Nevertheless, this could be a nice starting point for using NServiceBus in your application for this purpose.