Archives

Showing posts with label Azure. Show all posts
Showing posts with label Azure. Show all posts

Sunday, June 12, 2011

Testing Applications that use the AppFabric Caching Service in the Compute Emulator

One of the recent additions to the set of cloud services available as part of the Windows Azure Platform is the AppFabric Caching Service, and one of the interesting features of the AppFabric Caching Service is an ASP.NET session state provider. This is interesting because it offers a web-farm friendly session state provider, so if you deploy multiple instances of your Windows Azure web role, you now have a working, out-of-the-box, production quality session state provider (previously, if you deployed multiple instances, you had to implement your own, web-farm aware session management in your web role).

Using the AppFabric Caching Service session state provider in your Windows Azure application is simple. First, you need to set up a cache namespace using the Windows Azure portal:

CacheNamespace

Second, you must modify your application’s Web.config file with the necessary configuration to point to your new cache. This is easy to do, because you can copy and paste the necessary XML from the portal — just click on the View Client Configuration button:

ClientConfig

That’s it, no code changes are necessary for your application.

Once you’ve created your cache and updated your Web.config file, you’ll want to test it out. Probably, you’ll want to initially test it out using the local Compute Emulator rather than deploying your application to Windows Azure — so make sure that you configure two or more instances of your web role, and try it out. Unfortunately, you’ll find that it doesn’t work: when the local Compute Emulator switches to another instance, your session state disappears (and reappears if you are switched back to the original instance). It may help to display the current instance id somewhere in your UI to keep track of what’s happening, for example:

Instance: <%=RoleEnvironment.CurrentRoleInstance.Id  %>

It turns out that that the problem lies with the local Compute Emulator and the default settings for the session state provider. By default, the session state provider uses the value of HttpRuntime.AppDomainAppId when it builds its cache keys, and each instance in the local Compute Emulator has a unique value. If you add an additional attribute, applicationName, to your configuration, the session state provider uses this value instead of the value of HttpRuntime.AppDomainAppId and now everything works as it should:

<sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
   <providers>
      <add name="AppFabricCacheSessionStoreProvider"
          type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
          cacheName="default"
          applicationName="MyAppName"
          useBlobMode="true"
          dataCacheClientName="default" />
   </providers>
</sessionState>

This problem only manifests itself in the local Compute Emulator, you don’t need to use the applicationName attribute when you deploy your application to Windows Azure, although it doesn’t do any harm if it is there.

Read More >>

Monday, December 6, 2010

Another Cloud

Windows Azure and Amazon EC2

Having spent some time working with Windows Azure, I wanted to take a look at some of the other cloud environments out there to get a feel for how they work and how they differ in approach. The first platform I decided to take a look at was the Amazon Elastic Compute Cloud (EC2).

Amazon’s cloud offering is a little different from Microsoft’s — where Windows Azure is a platform and a specially designed framework that allows you to run specially written applications in the cloud, Amazon EC2 allows you to run standard operating systems virtual environments on Amazon’s servers. So two trade-offs spring immediately to mind:

  1. Windows Azure offers you a single fixed environment as against EC2’s almost completely free choice of operating systems (including Windows). Note that the latest Windows Azure release also includes Virtual Machine Roles in addition to the existing Web and Worker roles, so that you can run your own virtual machines in the cloud.
  2. The Windows Azure platform manages all the scalability issues for you (because of the features built in to the platform), whereas with Amazon EC2 you have to do a lot of the work if you want to build a scalable application that can run across multiple virtual machines. Although Amazon does offer an auto scaling service that can start up (or shut down) virtual machine instances for you based on demand, and a MapReduce service (for a description of the MapReduce algorithm and how to implement it in Windows Azure, see here) that’s designed to process large amounts of data on demand.

That said, there are a lot of similarities between the two platforms as I’ve outlined in the following table:

Windows Azure Amazon Web Services Notes
Content Delivery Network (CDN) Amazon CloudFront Both provide high-speed edge caches for static data, used for example to host video or other media for your cloud application.
Windows Azure Table Service Amazon SimpleDB Schema-less table storage.
SQL Azure Amazon Relational Database Service (RDS) SQL Azure is SQL Server in the cloud, Amazon RDS is MySQL in the cloud.
AppFabric Service Bus Amazon Simple Queue Service and Amazon Simple Notification Service Hosted queue services enabling  computers to exchange data through a cloud-hosted message hub.
Windows Azure Connect Amazon Virtual Private Cloud Creating virtual private networks that connect on-premises computers with your cloud instances.
Windows Azure Blob Storage Amazon Simple Storage Service (S3) Facility to allow you to store arbitrary data in the cloud.
Windows Azure Drive Amazon Elastic Block Store Storage that can be formatted and used like hard drives by your cloud application.

 

Daily News

Earlier this year I purchased a Kindle ebook reader which has been fantastic as a way to carry around books and reference material. However, one area that I was slightly disappointed with was the subscriptions to newspapers and journals that are available on the Amazon site. I soon found that I could generate my own news digests from just about any source by using an open source tool called Calibre. Once I customized the news feeds that I wanted to read on my Kindle, I can use Calibre’s command line interface to generate the file containing my news and email it direct to the Kindle. This is all great, except for the fact that I need to have the machine that generates the Kindle news feed using Calibre running. Most of the time it is running, but if on occasion I’m away from home without my laptop, it would still be great to get my daily fix of news delivered to my Kindle.

Calibre is very smart in the way that it generates ebooks containing news if you don’t mind doing a bit of python scripting, so I wanted to carry on using Calibre. Running Calibre on an Amazon EC2 virtual machine seemed like a good way to automate sending out daily news from an always on machine, so this gave me a reason to investigate how easy this would be to achieve with Amazon EC2.

Setting up my Cloud Machine with Amazon EC2

After signing up for EC2, the first decision was what operating system to use. Amazon currently has an AWS Free Usage Tier offer, which is only free if you use a Linux operating system, so Linux it was. However I was then faced with choice of several hundred different base virtual machines of various different flavours of Linux. Ubuntu seemed to be the most popular, and a bit of googling soon revealed which were the “official” Ubuntu machine images.

AMIs

Running my instance of Ubuntu on Amazon’s servers was a simple as selecting the base machine image and clicking the launch button in the web console (making sure I used a micro instance to make sure I stayed on the free usage tier). The Public DNS value is the machine’s DNS name.

MyInstances

The next step was to connect to my virtual machine, which involved some security configuration. First of all I needed a key and this was generated for me when I launched the virtual machine, secondly I needed to open up the virtual machine’s firewall to allow me administrative access so I added an entry on the Security Group page to enable SSH.

SecurityGroup

My only stumbling block came when I tried to connect to the virtual machine using Putty as an SSH client in Windows in that Putty didn’t recognize the key that EC2 had generated for me when I launched the virtual machine. It turned out that I needed to convert the key to a different format by using Puttygen. With that sorted out I could run a command shell on the virtual machine, and copy files to and from the virtual machine using PSCP.

Installing Calibre on Ubuntu turned out to a single command:

sudo apt-get install calibre

Finally I could set up a scheduled command using crontab to generate and email my Kindle newsfeed every day at 6am.

Conclusions

To summarize what I learnt from my first use of Amazon EC2:

  • Setting up a virtual machine in the cloud is very straight-forward with the Amazon Web Services web-based management console. It also looked as if would be quite simple using the command line tools.
  • Choosing a suitable base operating system is more difficult. Someone else has installed the OS and a selection of software before you start, you really need to know your way round the OS to be sure that it’s secure and properly configured. In fact you probably want to install it yourself, which is possible, but a bit more complicated. Also, it’s down to you to make sure everything is kept up to date with patches etc.
  • Given the choice of operating systems available, you can run just about any piece of software you like (even applications with GUIs if you use technologies like Remote Desktop or VNC). However, there’s no guarantee that it will scale — in order for an application to scale it must be able to run in multiple virtual machines simultaneously, and probably be designed to use one or more of the scalable storage services like Amazon SimpleDB or Amazon Simple Storage Service.
Read More >>

Thursday, December 2, 2010

Where Next with the Cloud?

I’ve spent most of this year embedded with a team run by Eugenio Pace in the patterns & practices group at Microsoft working on three books (with more to come). The first two have already been published — see the links on the right. You can also view the content on MSDN:

The first book includes an introduction to the Windows Azure Platform, and then describes how the fictional Adatum company migrates its existing ASP.NET expense reporting application to the cloud. The book looks at the mechanics of how Adatum performs the migration as well as examining the significant design decisions made by Adatum, the trade-offs it had to consider, and the cost implications. For example, the original, on-premises application used SQL Server as its data store. Adatum had to decide whether to go with SQL Azure for the cloud-based version of the application, which would be simple to implement, or expend more development effort to port the storage functionality in the application to Windows Azure table and blob storage.

The second book describes a “green field” scenario where the fictional Tailspin company is developing an online surveys application. With a new application, Tailspin in not constrained by any existing design decisions or implementation choices, but can chose which features of the Windows Azure platform to use. The design decisions addressed in the book include how to make the Surveys application a multi-tenant cloud application, and how to make the application scale on demand (for example to handle a customer creating a survey that they expect to get a million responses to in the week before Christmas). The Tailspin Surveys application will make a reappearance in a forthcoming book on Windows Phone 7 development, where a Windows Phone 7 device will become a client application enabling users to complete surveys on their phone.

Both books also have companion, downloadable code that you can use to explore exactly how these two companies chose to implement their applications for the Windows Azure platform, and hands-on labs that will guide you through some of the specific areas of the the implementations.

Next year, there will be third book on Windows Azure that will provide coverage of some of Windows Azure platform functionality not used by Adatum and Tailspin, for example the Access Control Service, and bring things up to date with some of the new features appearing in in the Windows Azure platform.

Read More >>

Monday, April 27, 2009

Live Mesh Part 2

In my previous entry about Live Mesh I mentioned that you could use it to transfer data to and from the cloud in addition to straightforward file-sync operations.

To develop Mesh enabled applications you need to sign up to the Mesh developer site, but this is straightforward. You do need to remove the Live Mesh client to install the Live Framework Client and connect to https://developer.mesh-ctp.com rather than http://www.mesh.com, but presumably this will be rectified for final release You can download the SDK from here.

In the Live Framework SDK there are samples to demonstrate Mesh functionality. The Live Folders sample creates, edits and deletes files from the Mesh. These files and folders appear exactly the same as the synchronized folders created with Live Mesh. I would expect that long term you could synchronize with these folders, but at the moment the Live Framework Client is sandboxed and does not support the synchronization or remote control features of Live Mesh.

The following code creates a Live Mesh folder and you can see that the resource type is LIVE_MESH_FOLDER:

public static string CreateRootFolder(Mesh mesh, string title)

{

// Check if a folder with the same name exists.

foreach (MeshObject oneObject in mesh.MeshObjects.Entries)

{

if (oneObject.Resource.Title.Equals(title))

{

return "Folder already Exists!!!";

}

}

// Create folder object

MeshObject meshObject = new MeshObject(title);

// It is a mesh folder

meshObject.Resource.Type = MeshConstants.LIVE_MESH_FOLDER;

// Add folder to collection of mesh objects

mesh.MeshObjects.Add(ref meshObject);

// Create feed for files (required)

DataFeed fileDataFeed = new DataFeed(MeshConstants.LIVE_MESH_FILES);

// Set type and handler type (required)

fileDataFeed.Resource.Type = MeshConstants.LIVE_MESH_FILES;

fileDataFeed.Resource.HandlerType = MeshConstants.FILE_HANDLER_TYPE;

// Add new data feeds to collection

meshObject.DataFeeds.Add(ref fileDataFeed);

//this.LoadMeshObjects();

return "Root folder " + title + " created successfully";

}


There is also a Project Manager sample in the SDK. This is a simple application to create projects and milestones. It creates non-standard objects in Mesh. As you can see in the project code below, you can create your own class of object and are not constrained by standard folders and files:


///
/// UUID of the parent MeshObject
///
[DataMember]
public string MOID { get; set; }
///
/// Title of the milestone (during save/update, this matches MeshObject.Resource.Title,
/// but is stored here when the custom object is databound instead of the resource)
///
[DataMember]
public string Title { get; set; }
///
/// Date when project will be started
///
[DataMember]
public DateTime KickOffDate { get; set; }
///
/// Estimated Date for Completion
///
[DataMember]
public DateTime CompletionDate { get; set; }
///
/// Date when project was shipped
///
[DataMember]
public DateTime ShippedDate { get; set; }
///
/// Description of Project
///
[DataMember]
public string Description { get; set; }


When you deploy a Mesh application it appears both on the users Live Mesh website and also as a shortcut on their desktop. In this way, a user can just run the app without any knowledge of Live Mesh. Furthermore, because the data is synchronized between the local machine and the cloud, they can run the application when they are disconnected and it will automatically synchronize when connected although there is no conflict resolution built in.

This does come with some caveats. This is currently CTP and is not fully functional. As previously mentioned the developer environment does not currently integrate with the Live Mesh client. Also every time I tried to run an application from the desktop it said it was waiting for me to sign in with no opportunity for me to do so and regardless of whether I was signed in or not. There is also a risk that this is a solution waiting for a problem. It looks interesting, it’s quick and straightforward to Mesh enable applications, but there needs to be a compelling requirement for this to go beyond the trying out samples stage and into developing real applications.


In the code samples above, these are just snippets of the complete solution, but you can see that Live Mesh has both straightforward user file and folder synchronization, as well as an API to enable you to create a cloud-based solution.
As a final note, I looked into this as a way to synchronize favorites in IE8. You can now do this by signing up to SkyDrive and reinstalling the Live Toolbar.

Read More >>

Monday, April 6, 2009

Live Mesh

I came across a new Windows Live component the other day called Live Mesh
when searching for a way to synchronize my favorites. In IE7 you could synchronize favorites with Live Favorites. It worked pretty well, although by no means perfectly. This functionality was removed from IE8, which annoyed me somewhat. I work from home most of the time, but occasionally go into the office and take a laptop. Virtually all documents I use are checked into SharePoint, so I don’t lose any data when I switch machines, however there are always useful bits and pieces that I pick up on the Web and I usually just add these to favorites. This is where the upgrade to IE8 is giving me problems. Not insurmountable, obviously, but I want everything to work smoothly. A blogger called Laurent Duveau has used Live Mesh to do just this. Looking further into Live Mesh made me realise its other capabilities. It interested me through a connection with the Azure Services Platform, of which it is a part, and through its data synchronization and remote control functionality.
Live Mesh allows you to synchronize folders with the cloud. You set up a device and then simply right click a folder to begin synchronizing data. This sounds a bit like functionality already provided by Live Sync and SkyDrive, however Live Sync requires both computers to be connected at the same time and SkyDrive is just online storage with no more advanced functionality.


So what more does Live Mesh offer? Well, for a start, the whole process is automatic and painless. You add a folder and the folder is synched. You can add another device and keep the data synched across multiple devices. These devices will include Windows Mobile and Apple Macs in the future. The data is both held locally, so that it can be accessed offline, and in the cloud, so that it can be accessed anywhere. This solved my favorites problem, but also made me curious as to the capabilities of Live Mesh.

Other features include remote desktop. Now not only do I have all my data synchronized, I can also connect to my desktop PC from anywhere. So far, these are all features available with the use of a few tools, but there is another trick up the Live Mesh sleeve. There is a Live Framework with various APIs including .NET, Silverlight and JavaScript to use Live Mesh services. This not only allows you to share folders as you normally would with Live Mesh, but also allows any data to be stored and synchronized between devices. I’ll leave the Live Framework for another day, but it appears to offer interesting possibilities.
Of course, this is a beta, but when the minor errors are ironed out this could be a valuable data synchronization tool.

Read More >>

Tuesday, February 10, 2009

The Service Bus

The Service Bus is one of the three .NET services available as part of Azure Services platform. At first sight there seemed to be a slightly daunting array of options for using the Service Bus, so here is a first attempt to try and pull the most significant elements together (with some notes after the table). For more detail check the original documentation which can be found here.

Service Bus Bindings (1)

.NET 3.5 WCF Equivalent Binding (2)

Optional HTTP connectivity mode (3)

Multicast Event Distribution

One-way Binding

Default Settings

Uri Scheme (8)

Client (Sender)

Channels

Service

(Listener) Channels

Data Channel Protection

SecurityMode options

Client and Service Authentication (6)

Reliable Messaging

BasicHttpRelayBinding

BasicHttpBinding

 

 

 

SOAP 1.1

WS-I Basic profile 1.1

http

https

80

443

Pair of secure socket connections to the cloud listener (5)

Transport

TransportWithMessageCredential

Yes

 

No

NetEventRelayBinding

N/A

Yes

Yes

N publishers

M listeners

Yes

SOAP 1.2 over TCP

.NET Framing

.NET Binary Serialization

sb

808

or

828 SSL

828 SSL

or

HTTP

(3)

Transport

TransportWithMessageCredential

Yes

No

NetOnewayRelayBinding

N/A

Yes

 

Yes

SOAP 1.2 over TCP

.NET Framing

.NET Binary Serialization

sb

808

or

828 SSL

 

828 SSL

or

HTTP

(3)

Transport

TransportWithMessageCredential

Yes

No?

NetTcpRelayBinding

NetTcpBinding

 

 

 

SOAP 1.2 over TCP

.NET Framing

.NET Binary Serialization

sb

SSL protected only in Relayed mode (7)

Choice of connectivity modes: Relay, Hybrid, Direct (9)

SSL protected only in Relayed mode (7)

Choice of connectivity modes: Relay, Hybrid, Direct (9)

Transport

TransportWithMessageCredential

Yes

Yes

(CTP version doesn't support this for Hybrid and Direct)

WebHttpRelayBinding

WebHttpBinding

 

 

 

Plain HTTP messages

Support for XML and Raw (binary) message encodings - supports REST

http

https

80

443

Pair of secure socket connections to the cloud listener (5)

Transport

Yes

No

WS2007HttpRelayBinding

WS2007HttpBinding

 

 

 

SOAP 1.2

Latest OASIS standards for Reliable Message Exchange and Security

http

https

80

443

Pair of secure socket connections to the cloud listener (5)

Transport

TransportWithMessageCredential

Yes

Yes

WSHttpRelayBinding

WSHttpBinding

 

 

 

SOAP 1.2

Draft WS-* standards for Reliable Message Exchange and Security as available at release of WCF 3.0

http

https

80

443

Pair of secure socket connections to the cloud listener (5)

Transport

TransportWithMessageCredential

Yes

Yes

Service Bus Bindings (1)

These are currently the available bindings in the .NET Services December 2008 CTP. Recommended binding is NetTcpRelayBinding.

.NET 3.5 WCF Equivalent Binding (2)

For the most part the 'Relay' bindings work in the same way as their standard WCF counterparts, except that the listeners are created in the cloud.

Optional HTTP connectivity mode (3)

Features the ability for a receiver to operate using just ports 80 and 443 if connectivity is locked right down. It implements a polling system to check for new messages.

ConnectivityMode

  • ConnectivityMode.Tcp: In this mode, all one-way and event communication is relayed over outbound TCP ports 828 and 808. SSL-secured traffic uses port 828, while unsecured traffic uses port 808.
  • ConnectivityMode.Http: In this mode, all one-way and event communication is relayed over outbound ports 80 and 443 using HTTP or HTTPS. This mode is the backup communication option for environments where outbound communication is constrained to HTTP/HTTPS, where outbound ports 808 and 828 are not available, or where the service/client cannot resolve external DNS names.
  • ConnectivityMode.AutoDetect: This mode automatically selects between the ConnectivityMode.Tcp and ConnectivityMode.Http, and favors TCP if it is available.

Listener Connection (5)

The SSL-protected control channel is using outbound TCP port 828, and the data channel is using outbound port 818. The data channel is SSL-protected if the endpoint URI scheme is "https" and the Security.Mode property is set to one of the EndToEndBasicHttpSecurityMode values Transport or TransportWithMessageCredential.

Security.Transport.RelayClientAuthenticationType (6)

This property controls whether clients of a service are required to present a security token issued by the Access Control service to the Service Bus service when sending messages. Services (listeners) are always required to authenticate with the Access Control service and present an authorization token to the Service Bus. If the service (listener) wants to take over the responsibility of authenticating/authorizing clients, it can opt out of the integration between Access Control and Service Bus by setting this property to RelayClientAuthenticationType.None. The default value is RelayClientAuthenticationType.RelayAccessToken.

Transport Channel Protection (7)

The transport channel protection guards all traffic to and from the Relay, but the data is visible to (but not observed by) the Service Bus infrastructure at the socket relay point. You can employ message security (Security.Mode=EndToEndSecurityMode.Message) to ensure that payload data is protected end-to-end without ever becoming visible to a third party (including the Service Bus infrastructure) at any waypoint.

Uri Scheme (8)

  • sb implies WCF on the client.
  • http/https support non-WCF clients.

Choice of connectivity modes (9)

  1. TcpConnectionMode.Relayed: In this mode, all communication is relayed through the Service Bus cloud. The SSL-protected control connection is used to negotiate a relayed end-to-end socket connection that all Client-Service communication flows through. After the connection is established, the Service Bus infrastructure acts much like a socket forwarder proxy relaying a bidirectional byte stream.
  2. TcpConnectionMode.Hybrid: In this mode, communication is relayed through the Service Bus infrastructure while the Client and Service endpoints negotiate a direct socket connection to each other. The coordination of this direct connection is governed by the Service Bus cloud service. The direct socket connection algorithm is capable of establishing direct connections between two parties that sit behind opposing Firewalls and NAT devices. The algorithm uses only outbound connections for Firewall traversal and relies on a mutual port prediction algorithm for NAT traversal. Since the NAT traversal algorithm is dependent on a very narrowly timed coordination and a best-guess prediction about the expected NAT behavior, the algorithm tends to have a very high success rate for Home and Small Business scenarios with a small number of clients and degrades in its success rate with larger NATs. If a direct connection can be established, the relayed connection is automatically upgraded to the direct connection without message or data loss. If the direct connection cannot be established, data will continue to flow through the Service Bus Relay.
  3. TcpConnectionMode.Direct: This mode is identical to TcpConnectionMode.Hybrid in the .NET Services December 2008 CTP. In a future release, this mode will use the direct connection only once and, if established, never relay any application data through the Service Bus Relay.
Read More >>

Friday, February 6, 2009

What are the options — Azure and Access Control?

I wanted to find out what the options were for building access control into an application hosted in the cloud, so that I could limit what was made available to different users of my Azure hosted application. More precisely I wanted to be able to use someone’s LiveID as the authentication mechanism, and use that to control which areas of the site that person could see or access.

Option 1 — Blob Storage in Azure

So what options are there in in Azure itself? Looking through the Azure SDK documentation there is a discussion of access control for Azure Storage Services, so I thought this might provide the basis of an access control mechanism. On closer inspection I realized that this wasn’t going to help. First of all access control is only available for Blob Storage, and not for Queue or Table Storage. Secondly, a blob can only be made public or private, with no finer control over who can see the blob’s contents.

If you do want to use the Azure Storage Services you do (with the exception of public blobs) need to authenticate your request using your Azure account credentials. Given that Azure Storage is accessed using a REST API this means providing your encrypted credentials as part of the HTTP request. There is some help provided with this in the Azure SDK samples: take a look at the StorageClient Sample. The sample includes a client library that wraps the REST API, and also shows how you can access the .NET Client Library for ADO.NET Data Services to access Azure Table Storage.

This example shows the type of code you would write to use a private blob, notice that the access control is set on the container, rather than the blob itself, and the useful utility method that pulls the credential information from your config file.

BlobStorage bs = BlobStorage.Create(StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration());

BlobContainer bc = bs.GetBlobContainer("list");

bc.CreateContainer(null, ContainerAccessControl.Private);

This code shows how you can then write to the blob using the sample client library, which is hiding all of the REST API from you:

BlobProperties props = new BlobProperties(txtItem.Text);

props.ContentType = "text/plain; charset=UTF-8";

BlobContents content = new BlobContents(Encoding.UTF8.GetBytes("This is the data to be stored in the blob!"));

bc.CreateBlob(props, content, true);

Option 2 — Membership Provider in Azure

The second option I looked at in Azure was to use ASP.NET membership. The default membership providers in ASP.NET use either SQL Server or Active Directory as their data sources, so neither are likely to work for a cloud hosted application. Digging around in the Azure SDK samples revealed this project here: AspProviders Sample. This project includes ASP.NET providers for Membership, Role, Profile and Session State. (Note: there is no ‘out of the box’ Session object in an Azure application because of the deployment model, this provider stores session state in Azure Storage.) The Membership and Role providers do exactly what you’d expect, and work with the standard ASP.NET Login controls. The providers use Azure table and blob storage to persist their data. This makes it very straightforward to set up authentication and authorization for your cloud application. What you would have to spend some effort on would be creating some administration tools to manage users and access control rules for the site.

Option 3 — Using Live ID with the Azure Membership Provider

My goal though was to use Live ID as my authentication mechanism, so is there a way of integrating Live ID with the Azure membership provider? My starting point here was to download the Windows Live Tools for Microsoft Visual Studio. The tools include a number of controls, in particular IDLoginStatus and IDLoginView, and a couple of new Visual Studio project templates: Windows Live Web Application and Windows Live Web Role (template for Windows Azure Cloud Projects) that looked useful. These two controls simplify using a Live ID to authenticate with your site, handling the redirects to the standard Live login page and back to your site. Although the controls a simple to use, there is a bit of setup to manage first. To start with you need to identify your site to Live and this requires a unique Application ID, a Secret Key and a return URL so that Live can redirect the browser back to your site after a successful log in. This can all be done at Live Services, where you can create a new project to define this information. You can then add an IDLoginStatus control to your page, and then chose the ‘Configure Application ID’ task to automatically add the Application ID and Secret Key to your web.config file.

The IDLoginStatus control has a ‘LoggedInLiveID’ property that tells you whether the user has logged in or not. What you can’t do is find out anything more about the user, other than their unique ApplicationUserID.

Is there a way to associate the ApplicationUserID with a user in the membership system, and so implement some access control on your site? This is where the second control, IDLoginView, comes in. This is a templated control with these templates:

  • AnonymousTemplate: the user is not logged in at all.
  • LoggedInTemplate: the user is only logged in using the ASP.NET membership system.
  • LoggedInIDTemplate: the user is only logged in with a Live ID.
  • LoggedInAllTemplate: the user is logged in with both the ASP.NET membership system and with a Live ID.
  • AssociatePromptTemplate: the user is prompted to associate their Live ID with their membership id.

The control can also be configured to automatically associate their Live ID with their membership id, and once the association has been made then then logging in with Live automatically logs the user into the membership system. So from then on I have a site that uses a Live ID for authentication, and ASP.NET membership to control access.

I got all of this working in a standard ASP.NET application, and then tried it in a cloud application and this is where I got stuck. The IDLoginView control sets up the association between the membership ID and the Live ID by adding a new table ‘aspnet_LiveIDAssociation’ to the ASPNETDB database, and assumes that the membership provider is the standard SQL membership provider. Running in the cloud, I’m not using the standard membership provider, so any attempt to add an association fails. To get this scenario to work I’d probably have to modify the sample Azure membership provider and handle a lot of the Live ID login process manually…

Option 4 — Using Live ID and the Access Control Service

Access Control Service is one of the cloud infrastructure services (along with the Service Bus and Workflow Service) that are part of the Azure platform. The Access Control Service is ‘a hosted, secure, standards-based infrastructure for multiparty, federated authentication and rules-driven, claims-based authorization’. I wanted to see if I could use it as an access control mechanism for a web site where I was authenticating users with Live Id.

To adopt some of the correct terminology, the Access Control Service is a Security Token Service (STS) and my web application is a relying party (RP). To briefly summarize how this process will work:

  1. My site prompts the user to login to the Access Control Service with their Live ID.
  2. The Live ID is mapped by the Access Control Service to set of claims (permissions) defined by me.
  3. The request is redirected back to the original page on my site. Elsewhere on my site the claims can be examined, and the appropriate logic applied to determine what the user can see or do.

There are a couple of important points to note at this point:

  • This process is complicated. Trust relationships must exist between the various parties; the Access Control Service is pre-configured to trust the Live Id system, but I have to define the trust relationship between my application and the Access Control Service. Information transferred between the sites must be secure.
  • The system is standards based, meaning that other authentication and authorization systems could be plugged in.
  • My application has completely outsourced the authentication and authorization rules. All my application needs to do is examine an incoming claim, such as ‘this person is an administrator’, and decide on the basis of that claim whether the user can see that page or perform that action.

There is no configuration needed for the Live ID login because there is already a trust relationship setup for Access Control Service, but I did have to code the login rather than use the IDLoginStaus control:

string homeRealm = "http://login.live.com";

string scope = "http://localhost/LiveACS/";

string acs = "https://accesscontrol.windows.net/passivests/YOURSOLUTIONNAME/LiveFederation.aspx";

 

var request = new SignInRequestMessage(new Uri(acs), scope);

request.Parameters.Add("whr", homeRealm);

 

Response.Redirect(request.RequestUrl);

The homeRealm is reason we can’t use the IDLoginStatus control, because the current version of the control doesn’t support the whr parameter.

The scope is used to match to a set of rules in your Access Control Service solution, and the solution name must be part of your Access Control Service address.

You can manage your Access Control Service solution here. You define a scope to hold a collection of rules, and a rule is made up of input claims (in this case a Live ID) and an output claim (in this case an Action), you also need to upload the public key of the certificate you will be using to encrypt the claim information that will be transferred to your application. (Note: if someone logs in but no input claims are matched here, then all they’ll see will be a standard 403 message).

Input Claim
Type: Windows Live ID Value: someone@liveid.com Issuer: live.com

 

Output Claim
Type: Action Value: LiveACS.ViewData Issuer: accesscontrol.windows.net/YOURSOLUTIONNAME

At this point I need to introduce another component. So far I’ve set up my site to enable logins using Live ID, the login can be used by the Access Control Service to identify a  set of claims to be encrypted and transferred to my application. How can a decrypt and understand the claims in my application? I could use WCF and the System.IdentityModel.Claims namespace, but the recommended approach seems to be to use the new Geneva Framework and the Microsoft.IdentityModel.Claims namespace for this job instead.

Once the Geneva Framework SDK is downloaded I ran the FedUtil.exe utility to update my web.config file:

<microsoft.identityModel>

  <audienceUris>

    <add value="http://localhost/LiveACS/" />

  </audienceUris>

  <issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry">

    <trustedIssuers>

      <add thumbprint="416e6fa5d982b096931fbf42c4a3dcd608856c95"

           name="http://accesscontrol.windows.net/YOURSOLUTIONNAME/"/>

    </trustedIssuers>

  </issuerNameRegistry>

  <federatedAuthentication enabled="true">

    <wsFederation passiveRedirectEnabled="true" issuer="https://login.live-int.com/login.srf" realm="http://localhost/LiveACS/" />

  </federatedAuthentication>

  <applicationService>

    <claimTypeRequired />

  </applicationService>

  <serviceCertificate>

    <certificateReference x509FindType="FindBySubjectDistinguishedName" findValue="CN=localhost" storeLocation="LocalMachine" storeName="My" />

  </serviceCertificate>

</microsoft.identityModel>

It added a bit more than what I’ve shown above – setting up various imports and modules – but these are the important elements. audienceUris determines where the tokens containing the claims will be sent. trustedIssuers specifies whose tokens we should trust. serviceCertificates identifies where to find the private key to decrypt the token that came from Access Control Service (this is the private key corresponding to the public key I uploaded to the scope).

Once all that is in place I can examine the claims in code and control access to parts of my site like this:

if (ClaimsVerification.ViewDataPermission) Label1.Visible = true;

Which uses a simple utility class:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using Microsoft.IdentityModel.Claims;

using System.Threading;

 

public class ClaimsVerification

{

    public static Boolean ViewDataPermission

    {

        get

        {

            IClaimsIdentity identity =

                Thread.CurrentPrincipal.Identity as IClaimsIdentity;

            if (identity == null) return false;

 

            return identity.Claims

                .Where(claim => claim.ClaimType.Equals("http://docs.oasis-open.org/wsfed/authorization/200706/claims/action") &&

                       claim.Value.Equals("LiveACS.ViewData"))

                .Count() > 0;

        }

    }

}

The ClaimType here is the full name of the ‘action’ type output claim I defined in the Access Control Service scope.

Can I use all this in a cloud application as I wanted? Unfortunately not yet – the reason being that the Geneva Framework classes are not available as part of the cloud services at the moment, so I guess I’ll just have to be patient!

Read More >>