Azure Service Bus WRAP Token Renewal

Service Bus samples and documentation often cover how to request a token from Access Control Services via REST. Here we touch on caching said token, and consider its renewal upon expiry.

The .NET Azure Service Bus API, from the Microsoft.ServiceBus and Microsoft.ServiceBus.Messaging namespaces, provide a number of useful abstractions when developing a brokered messaging solution. The API is nice, because is lets you focus on the business problem at hand, while keeping the boilerplate, protocol related interaction nicely tucked away. Example:

Now when it comes to using to the REST API, which (as REST intends to) opens up potential service bus consumers/publishers to literally any platform (WP7, Linux, OSX, etc) or language (ruby, C++, python, pre .NET 4.0, etc) , that supports a basic HTTP stack. However, with this, we loose the abstracted (i.e. take care of it for me) approach to dealing with the service bus. There are two fantastic resources in regards to getting started with the REST API. First the offical Azure Service Bus REST API document. Second the Silverlight samples provide fully functional peek-lock REST implementation. Third enable Fiddler2 for SSL; tracing conversations between ACS and the Service Bus has been invaluable and saved me hours of diagnostics.

One particular area that requires some thought that I have found that samples don’t address, is around token management. The samples do a great job highlighting how to obtain a WRAP token, something similar to this does the trick:

There after, any communication that takes place with the Service Bus needs to present this WRAP token by stuffing it into the Authorization HTTP request header.
For reference, here is a WRAP token response from ACS. This particular token asserts the Listen, Manage and Send claims for interacting the with “footopic” Service Bus Topic.

1199 is time in seconds, which is about 20 minutes. So to prevent having to make an ACS call everytime your code exchanges messages with the service bus some sort of caching strategy is recommended. It would be difficult/inaccurate at best to implement some sort of client side timer that determines how much more of the 20 minute window remains. A more robust way that we have used successfully, is to continue optimistically re-using the token, until the service bus yells at you (i.e. an HTTP Unauthorized or a 401) stating the token is no longer valid.

Here’s a sample topic send operation, when the token is still valid (this same token will work for about 20 minutes).