Validating a WRAP ACS token in node.js

A few friends and I are building a system for home automation. Specifically, it is an application that opens and closes a garage door. One of the design decisions was to write the server side in node.js but to use Azure when it made sense. One of the Azure features we are using is the Access Control Service. When a client presents a token, you need to make sure that the signature on that token is valid. That turns out to be fairly interesting if you are new to node.js and have never used it before. I fit that model well. After a lot of tinkering and learning, I was able to write a function that validated a wrap_access_token using node.js and some associated, standard libraries. Here is the code, in its entirety. I include some ‘test’ code as well to allow others to verify results. I’ve already rotated the ACS signing key so that I don’t breach security too badly. This whole thing works surprisingly well.

In case you can’t read the code too well, here is what it does:

1. Parse the token into it’s constituent parts.

2. Pass the wrap_access_token to the function, along with the associated key.

Within the function:

1. Remove the signature part from the token since we need to verify that we generate the same signature. Since the signature is generated based on the bytes that precede it, the signature can’t be part of itself (this part is obvious when you think of it; the hard part is remembering to think of it!)

2. Unescape the signature and remember the base64 version of the signature, which is really just a byte array.

3. Generate the SHA256 HMAC signature using the shared secret/key.

4. Verify that the base64 encoding of the digest that we generated matches the one that was sent it.

5. If the signature passed in matches the one we generated, then the other entity knows the secret and can be trusted to have signed the tokens.

6. Party on, because the claims are valid.

The code would next need to split out the claims. The claims are just form-encoded key value pairs within the wrap_access_token. That step is left as an exercise for the reader.

var crypto = require(‘crypto’);
var util = require(‘util’);
var querystring = require(‘querystring’);
var buffer = require(‘buffer’);

function ValidateToken(token, key){
var hmacToken = “&HMACSHA256=”;
var indexOfToken = token.indexOf(hmacToken) + hmacToken.length;
var swtSignature = querystring.unescape(token.substr(indexOfToken, token.length – indexOfToken));
var signedPiece = token.substr(0, indexOfToken – hmacToken.length);
var buffer = new Buffer(key, encoding=”base64″);
var hmac = crypto.createHmac(“sha256″, buffer);
hmac.update(signedPiece);
var digest = hmac.digest(encoding=”base64″);
return digest == swtSignature;
}

var theToken = “wrap_access_token=developersmackdown.garage%3dOpenClose%26http%253a%252f%252fschemas.microsoft.com%252faccesscontrolservice%252f2010%252f07%252fclaims%252fidentityprovider%3dhttps%253a%252f%252ffriseton.accesscontrol.windows.net%252f%26Audience%3dhttp%253a%252f%252fcontosocontacts%252f%26ExpiresOn%3d1325287532%26Issuer%3dhttps%253a%252f%252ffriseton.accesscontrol.windows.net%252f%26HMACSHA256%3dSrgqXJv9pkxjweT2Lr%252bIV%252fGAncqIc34SnbrHdbr3VOQ%253d&wrap_access_token_expires_in=5999″;
var theData = querystring.parse(theToken, sep=’&’, eq=’=’);
var theKey = “Bn7TfLML5wK+R5TAa2VrO/9JANwuk3lzt/ykc4no+h0=”;

util.puts(ValidateToken(theData.wrap_access_token, theKey));

Leave a comment

REST Presentation at Chicago Software Development Community in Oakbrook

Thanks again to everyone who showed up for my presentation on REST at the Microsoft Store in Oakbrook. I’ve posted the slides and demos here. It was a great time. I’ve never presented in a store, never had a component of the “audience” that was just shopping either. It was an interesting, unique experience to say the least! I also enjoyed the conversations afterwards.

Leave a comment

My Windows Azure Caching Service talk from DevConnections

I just presented my Windows Azure Caching Service talk. Thanks to everyone who attended. The audience was small, but I love that you all asked so many great questions. Here are the slides and demos from the talk. I’ll be giving this talk again at the Midwest Cloud Computing User Group in the Chicago area on November 15. You can register for it at http://www.communitymegaphone.com/ShowEvent.aspx?EventID=4709.

The slides and demos from the content at DevConnections is here.

Leave a comment

Talk and demos from CNUG, AppFabric Talk

Last night I had a chance to speak about Windows Azure AppFabric at the Chicago .NET Users’ Group. Thanks to everyone who came out! I had a great time. A few of you really wanted the slides ASAP. I’ve cleaned out my keys and namespaces from the demos, so they don’t run at the moment (but they will build!). You can get them here: https://friseton.blob.core.windows.net/downloads/CNUG-AppFabric-2011-07-20.zip.

You’ll need to install a few things and create a few accounts if you want to run any of the demos:

Tools:

1. Getting started links for Windows Azure: http://www.microsoft.com/windowsazure/learn/getstarted/

2. Windows Azure AppFabric SDK 1.0: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=19925 (for production AppFabric)

3. Windows Azure AppFabric SDK 2.0: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=17691 (for the CTP bits: queues, topics, etc.)

4. More training on Windows Azure: https://www.pluralsight-training.net/microsoft/OLT/subscribe/Subscribe1.aspx?freetrial=true&planHint=Monthly (10 day free trial– totally worth it, but I am an instructor there too;) )

Leave a comment

AppFabricLabs and the ServiceBus

This week, the Windows Azure AppFabricLabs was updated. The major updates are that the Service Bus labs environment now uses v2 of the Access Control Service and topics/queues have been created. This pushes the number of queueing solutions on Azure to 3:

* Queue Storage

* Message Buffer

* Queues

The main difference between the types of storage relates to size and usage patterns. Queue storage allows for messages up to 8 KB in size and is primarily intended for applications running on Azure. The service only accepts one type of credentials, and you probably don’t want to share those.

The Message Buffer stores messages of up to 60KB for about a minute. It is great for volatile queues as a short lived rendezvous point for exchanging messages. This service lives on the Service Bus and allows for authentication with the Access Control Service.

The Queues implementation in the Service Bus allows for larger messages (up to 256 KB) which can last for a longer period of time. Interacting with the queue feature is pretty simple. Go to the https://portal.appfabriclabs.com page and allocate a Service Bus namespace. The ‘Hello, World’ for the queue looks like this:

static void Main(string[] args)
{
  var sbNamespace = "your namespace";
  var credential = TransportClientCredentialBase.
    CreateSharedSecretCredential("owner", "[your key]");
  var uri = ServiceBusEnvironment.CreateServiceUri("https", sbNamespace, 
    string.Empty);
  var client = new ServiceBusNamespaceClient(uri, credential);
  var messagingFactory =
    MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", 
    sbNamespace, string.Empty), credential);
  var queue = client.CreateQueue("demo");
  var queueClient = messagingFactory.CreateQueueClient(queue);
  var sender = queueClient.CreateSender();
  sender.Open();
  sender.Send(BrokeredMessage.CreateMessage("test"));
  sender.Close();
  var receiver = queueClient.CreateReceiver();
  receiver.Open();
  var message = receiver.Receive();
  receiver.Close();
  Console.WriteLine(message.GetBody<string>());
}

Leave a comment

Integrating with the Camera in WP7

There has been a small white lie that many people tell when looking at whether or not a WP7 application can directly interact with the camera. The fib looks like this:

You can only access the camera through the CaptureCameraTask. Direct access is not allowed.

It didn’t seem right when I heard that, so I did some digging around, looking for ways to find out what is really contained in the phone. Some information is out there, and if you assemble the parts, you wind up with a better view into what managed code can do on the phone. I wrote a post earlier that showed what you need to do in order to make your development environment work better. As a result of that effort, you are going to be able to use the camera in your Windows Phone 7 applications today.

Adding live support for a phone is actually pretty easy. You just need to add some references to the right assemblies, add a little markup to your page, and then write a few lines of code.

References

Go ahead and create a WP7 XAML app. Once you do that, you need to add references to two assemblies that aren’t standard issue:

* Microsoft.Phone.InteropServices

* Microsoft.Phone.Media.Extended

Why two assemblies? The first one allows you to work with the second one-nothing more.

Add some markup to display the camera

To work with the camera, live, here is what you do:

1. Add a reference to the Microsoft.Phone.Media.Extended to the page you want to display the camera output to. For example, add the following to the PhoneApplicationPage element:

xmlns:media=
"clr-namespace:Microsoft.Phone;assembly=Microsoft.Phone.Media.Extended"

2. With that in place, you can then put a CameraVisualizer on to your page. A CameraVisualizer displays the content of a camera on to a surface.

<media:CameraVisualizer Name="cameraVisualizer" Visibility="Visible" 
    Margin="64,4,99,26" Height="426" Width="593" />

Hook up the Camera to the Page

In your page’s code behind, add a Microsoft.Phone.PhotoCamera and attach it to the CameraVisualizer. You do that by calling SetSource on the visualizer. The code looks like this:

cameraVisualizer.SetSource(_camera);

 

Doing something with the Camera

From there, you can access methods telling you what is going on with the camera:

* ShutterPressed: Fires when someone presses the camera button.

* ImageSavedToDisk: Fires when the image you just took is saved to disk, passing along the path to the file.

* ThumbnailSavedToDisk: Fires when the thumbnail is saved. This one also has the image path.

When the shutter is pressed, you still need to tell the camera to take the picture. To do this, fire the CaptureImage method on the PhotoCamera instance. You can also do some cool things like set the flash setting, zoom level, and auto focus.

There are a few gotchas with the camera that do make it difficult to work with and show why it wasn’t available to all of us when the phone launched. First off, any time you use the control just a little bit ‘incorrectly’, you will see a COM exception. Second, any time that the visualizer goes off screen then back again, you need to detach any events, then hook them back up again or you will have a bad experience for your users. If you do not handle the pictures being taken in quick succession, you will have issues.

I invite you to play with the camera but be warned-it is a nasty beast to work with and you will spend quite a few cycles fixing weird little bugs. Microsoft never made a general release of this code because the code needed more QA before burning any cycles documenting the feature. They’ve already announced it will be in better shape for Mango, but if you want to use it now, I’ve given you enough rope. Have some fun (and don’t hang yourself)!!!

Thanks to Jeff Prosise for encouraging me to talk about this. We were chatting in late April at a conference when I was having some fun with a WP7 camera app I had written and he said he wanted to know how I did that.

Leave a comment

The Windows Azure AppFabric CTP For May has Shipped

The May 2011 AppFabric updates have shipped. You can get them all from here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d89640fc-c552-446e-aead-b1e0d940f31b. Coverage is exploding over at TechEd, Clemens Vasters can finally talk about topics, and it’s a grand day. So, many of you will be digging into the source and will want a CHM file that works. The that you download will be blocked from showing Internet content and when you open it, you will see something like this:

image

If you do see that ‘Navigation to the webpage.’ message, here is what you’ll need to do.

1. Right-click on the CHM file and select ‘properties’.

2. On the General tab, there is a button WAAAAAAYYYYYYY at the bottom labeled Unblock. Click that button so that the content from the Internet will display just fine on your PC.

SNAGHTML24f3d3a

3. Reopen the CHM and you’ll be able to actually view things.

Leave a comment

Follow

Get every new post delivered to your Inbox.