Federated Authentication with Azure AppFabric ACS v2.0: Part 1 - Setup
Yesterday and today I've been teaching the Azure introduction training for MIC Belgium. Even though Azure AppFabric ACS wasn't part of this course it was a hot topic. I showed a demo and we did a small exercise all together, but I promised to create a detailed guide that allows you to create your own applications using federated authentication.
Prerequisites
Before we get started you need a few things on your machine. I was surprised to notice that two of the participants were still running on Windows XP. If you're trying to develop with Azure or WIF then XP is a NO GO. So here is what you need to get started:
To my surprise the WIF SDK does not contain the runtime, so you'll need to install that first.
For the IIS Metabase you'll need to go to Control Panel and choose to turn Windows features on or off:

Creating a simple ASP.NET Website
Start Visual Studio 2010 as Administrator and choose new project to create a normal ASP.NET website. You could use a cloud project but this guide will work with a regular ASP.NET website. After you see the project in the Solution Explorer right click the project and select properties. You'll need to adapt the Web settings to configure IIS.

We're doing this because you might have some problems with Cassini (development webserver) when working with regular (non-MVC) sites and ACS.
- Go to the web tab
- Choose Use Local IIS Web Server
- Click Create Virtual Directory
Now your application should be linked to IIS and if you press F5 everything should work correctly.
Creating an Azure AppFabric ACS namespace
Now that we have a working application it's time to configure Azure AppFabric ACS. ACS will allow us to use identity providers for authentication in our application without having to worry about the management of the identities. One of the goals of federated authentication is that we outsource the identity management. You'll see soon enough what I mean.
Connect to the Management Portal (http://windows.azure.com) and go to the AppFabric tab

Click the Access Control node in the left menu and choose New Namespace. A namespace will allow you to define identity providers and link them to relying party applications (more on this later). Here is an example of how you would create the namespace:

You'll get to set up the name (single word in lower case), choose your subscription and also choose in which datacenter the namespace will be hosted. Before you can create the namespace you need to click the Check Availablity button so see if the namespace you entered has already been taken or not. Click the Create Namespace button and wait a few seconds until the namespace is created.
When the status changes to Active you'll need to select the newly created namespace and click the Access Control Service button. This will forward you to the ACS configuration page and this is where you'll do the actual configuration.

Configuring the relying party application
A relying party application would be your site for example. This site would use ACS to implement federated authentication. But in the end your relying party application will be using claims that come from the identity providers you configure in ACS. You should see a claim as a piece of information about someone's identity. This could be a person's name, function or birthdate for example.
Before defining the relying part application we need to see if the identity providers have been set up correctly. Go to the Identity Providers tab and you should see Windows Live ID to be active be default. Lets leave this how it is for now.

Now go to the Relying party applications tab and choose to add a new one. For the realm and the return URL you should use the URL of your website (for the Visual Studio project that is still open you can just press F5 and you'll see the url of the application). For the application I'm creating this is http://localhost/Sandrino.Labs.ACS/

Besides that you should also select the identity provider(s), but since we only have Windows Live ID (and this is selected by default) you won't need to do anything here for now. Later on the article I'll show you how to add other identity providers, but that's not important for now. Press the Save button and the relying party application will be created.

Now in the left menu click the Rule groups tab. This tab allows you to define the mappings between claims from different identity providers and your relying party application. You should have a default rule group that was created for your relying party application. For my current project this rule group is named Default Rule Group for Labs ACS. Click the name of the rule group to open it.
Press the Generate button, choose Windows Live ID and you'll see that a rule was added matching the nameidentifier claim.

That's it for the ACS configuration for now. The relying party application we configured will now be using Windows Live ID as identity provider and we also have a claim (nameidentifier) that will be accessible from our ASP.NET application. Let's now see how we can use ACS in our application.
Using ACS in our ASP.NET application
If you installed WIF and the WIF SDK correctly you should see the Add STS reference option when you right click the project:

Click this options and you'll see a wizard popping up. On the first page you'll need to configure the Application URI like you configured it in the cloud. This is how I did it:

Before you can continue to the next step you'll need to go back to the ACS configuration page. Click the Application Integration tab and copy the following URL. You need to paste this URL ond the "Use Existing STS" part of the following wizard step.

Now go back to the STS reference wizard and press Next. You'll see the warning message "The application is not hosted on a secure https connection." because you're running on regular HTTP. Ignore this for now by pressing No, but understand that you should always use HTTPS for production applications. On the next page paste the URL you copied from ACS:

Finally press Next until the wizard disappears. This means that both encryption and validation will be disabled but that is ok for now (since we're just developing and exploring ACS). Remember that in an actual production environment your security should be optimal.
If you take a closer look at your project you'll see a new directory called FederationMetadata which contains the referenced FederationMetadata.xml file.
Start your application and see what happens. If everything went we'll you might see a Windows Live ID homepage where you can enter your credentials and after logging in you'll get a nasty ASP.NET error. Should your Windows Live ID password be saved you might not even see the Windows Live ID homepage but see the error immediately.
Fixing the errors
You might run into a few errors, so let's fix these before we continue.
A potentially dangerous Request.Form value was detected from the client (wresult="<t:RequestSecurityTo...").
To solve this problem we simply need to change the request validation mode. Open the web.config and add the following line before the end of the system.web element:

Load User Profile errors
If you're running IIS 7.5 you might run into Load User Profile errors. This is easy to fix: find which application pool your website is using and adapt this pool to support loading of user profiles.
When you select the application pool you need to choose the advanced settings. Here you can see how I'm editing the ASP.NET v4.0 (this should be the one by default) application pool:

This should solve most of your problems. Now try to run your application again, log in to Windows Live and you should be redirected back to your application. You're done! The ASP.NET application you built requires the user to be authenticated and since the relying party application configured in ACS only supports Windows Live ID you'll be forwarded automatically to Windows Live.
Let's see how you can add other identity providers (like Google).
Adding more identity providers
Go back to the ACS configuration page and click the Identity Providers tab. In this example you'll need to add both Google and Yahoo as identity provider. When you add these providers you'll see that the default values of these providers will automatically link these identity providers to your relying party application.

Now to be able to use these identity providers you'll need to configure the claims. Go to the rule groups tab and choose the current rule group (for me this is Default Rule Group for Labs ACS). Now press the Generate button. Pressing the Generate button will make sure ACS automatically generates a list of available claims for the chosen identity providers. The result is clear:

You'll see that we have different types of rules. Each identity provider has a nameidentifier (which we could use as unique key to identify the current user, more on this later). Besides that you can also see that both Google and Yahoo also give you access to other metadata of the identity like the email address or the name.
The identity providers have been added in ACS (and also automatically added in our relying party application) and the claims have been set up. Remember if you are using ADFS or any other system you can modify the rules (under the Rules Group tab) to start mapping claims. This is an important job because your application could/should work with a fixed set of claims independent of the identity provider. That's why we need to do the mappings in ACS (if required).
Final test
When you ran the application the last time you saw that you were forwarded automatically to a Windows Live login page. Now we changed the configuration in ACS to also allow authentication from Google and Yahoo. Please start the application without changing anything and I'm sure you'll be surprised by the result:

Isn't this great? Without changing anything to your code you just allowed users from Yahoo! and Google to use your application. And since ACS also provides support for Active Directory Federation Services you could also allow access from your corporate domain accounts. This last example will be important when you decided to host enterprise applications in the cloud and you need your domain users to access the application.
What's next?
Try these steps for yourself. In the next article I'll show you how you can leverage the Windows Identity Foundation API to access the claims and their values to create a real application using ACS.
Enjoy...
Slide deck for my session at Belgian Dynamics Community - Connection Day
Last week I got the opportunity to speak at the Belgian Dynamics Community Connection Day: The Inevitable Cloud
19:30 - 21:00
CRM track - Integrating CRM Online and ERP systems using Windows Azure
RealDolmen
As of January 2011, Microsoft Dynamics CRM will also be available as a SAAS solution. Organizations are ever more attracted to moving out a vast series of business applications to the cloud. This trend however introduces a new level of complexity when it comes to systems integration. This session will give you step by step guidance on how to integrate an on premise ERP application with Microsoft Dynamics CRM Online using the Windows Azure Service Bus.
The live demo with Windows Phone 7, Azure AppFabric and CRM Online turned this into a fun session where everything actually worked like we wanted.
Download: RealDolmen BDC 2010-12-09 - CRM Track.zip (1.92 mb)
Important event: Cloud Applications with Windows Azure Jump Start
After the Silverlight Firestarter online event now it's time for Azure...
Microsoft is organizing a 3-day online event on 15-17 december with a single focus: Azure.
The teachers:
Day 1 (Sign up):
Windows Azure Overview
Introduction to Compute
Windows Azure Lifecycle | Part 1
Windows Azure Lifecycle | Part 2
Day 2 (Sign up):
Windows Azure Storage | Part 1
Windows Azure Storage | Part 2
Introduction to SQL Azure
Windows Azure Diagnostics
Day 3 (Sign up):
Windows Azure Security | Part 1
Windows Azure Security | Part 2
Scalability, Caching & Elasticity
ASP.NET Hands-On Lab Walkthrough
I just hope these sessions will also cover the new Azure features!
Enjoy..
Code metrics and more with NDepend
Introduction
Do you know the quality of the project you're currently working on? Sure you can have guidelines and rules... but projects where a few people have worked on for a few weeks/months/years tend to live their own life here and there. Maybe the team had to catch a deadline for the latest sprint, or the lead developer was on holiday and the problem had to be solved using a quick and dirty solution, ... Every project will have its own little exceptions to the rules and guidelines.
But it should be possible at a certain point in time to measure how good (or how bad) the project is being developed. And this is where NDepend comes in. Quote from the NDepend site:
NDepend is a Visual Studio tool to manage complex .NET code and achieve high Code Quality. With NDepend, software quality can be measured using Code Metrics, visualized using Graphs and Treemaps, and enforced using standard and custom Rules.
Hence the software design becomes concrete, code reviews are effective, large refactoring are easy and evolution is mastered.
Installation
To install NDepend you just download a zip file, install it, copy your license in the root of the directory (if you have one) and you're done. Afterwards you have to go and read QuickStartTutorial_NDepend.txt to see how you can install the Visual Studio addin. This is a personal choice but I'm not too fond of XCOPY deployment. I would rather have had a regular setup wizard where I could just check or uncheck the Visual Studio 2010 integration.
Patrick Smacchia (the creator of NDepend) wrote a nice article regarding why he chose XCOPY deployment: http://codebetter.com/blogs/patricksmacchia/archive/2009/08/10/the-benefits-of-xcopy-deployment.aspx
Now that I installed the application and the AddIn we can continue.
Mode 1: VisualNDepend
In the NDepend directory you'll find the file VisualNDepend.exe, this is the standalone application.
Since NDepend uses DevExpress as control library you can easely make a few changes to the UI. I decided to go for the black ribbon, here is the result:

In the rest of the article I'll be using the standalone application.
Mode 2: NDepend AddIn
NDepend also integrates with Visual Studio 2010. It doesn't seem to provide extra functionality but it integrates very well with the solution you're currently working on.

Also when you right click a project you get tons of functionalities that directly apply to that project:

Analyzing a real project
I'm currently working on an ASP.NET project that was completed about a year ago. The goal here is to start refactoring so that we can easily move to Silverlight in the future. NDepend is based on analysis of assemblies, but when you create a new NDepend project you can also open a Visual Studio solution which will in turn add all projects as assemblies to be analysed.

After loading the solution the external references will also be resolved automatically. And that's it. Now you can hit the button Run Analysis to get started. After a few seconds / minutes the analysis will be done and you'll have a complete overview of your solution.
HTML Report
The first thing you'll see is an HTML report containing all the information:
- Overview of the application metrics
- Overview of the assembly metrics
- A VisualNDepend view
- An assembly dependencies diagram
- And much much more!
The fact that the report is generated automatically is great (we're working with SharePoint to store all our documents). If you're working with a team at your customer you can easily share the analysis report with the local team.

Code Query Language
NDepend introduces the concept of Code Query Language (CQL). This language allows you to create reports of the analysis as if you were working with SQL.
WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE
CyclomaticComplexity > 20
ORDER BY CyclomaticComplexity DESC
Just like Visual Studio comes with a standard set of snippets, NDepends comes with a standard set of queries (more than 100!).

Analyzing the output of a query
The set of standard queries contains a lot of interesting queries you can use for each project. One of the most interesting is the query Do not raise too general exception types. It's true that when you want to do some quick tests or you're not that experienced with exception handling you tend to use Exception a lot. But it is a best pratice to use your own type (for example CreditLimitReachedException) instead of the default Exception / ApplicationException.

When I ran the query NDepend provided me with the list of methods that were using these global exceptions:

After double clicking a method NDepend will bring up Visual Studio, open the right file and jump to the right line. You can start fixing your code right away!

In the introduction I talked about rules and guidelines. Well, thanks to CQL the person in charge could create some queries that check if the rules and guidelines are followed correctly.
Code Coverage
An other great functionality of NDepend is that you can track your code coverage. When you're writing unit tests you want to be sure that your tests cover all the code. NDepend will give you a visual overview of all your methods and their coverage and you can even create reports. This is useful for when you want to find all methods with a coverage percent less than 50, create a report out of this data and sent it to your test team:

Much more
I covered a few interesting features of NDepend but there's still much more to discover:
- Dependency Graph
- Dependency Matrix
- Visual Metrics
- Comparing with previous analysis (to see how the project evolved)
- MSBuild integration!
- ...
Documentation
Blogs and documents:
Videos:
Alternatives
The only alternative to NDepend I know is Microsoft's FxCop. A great feature of FxCop is its integration with TFS.
Conclusion
NDepend is a great application with an unbelievable amount of features. Everything you see in the application can be exported one way or the other (be it HTML, PNG, XLS, ...) which is great. Seeing visual representations of the analysis will also help you get a better view of things. And with CQL you can really enforce your company's own rules and guidelines throughout multiple projects. The code coverage support is great and I truly love the MSBuild integration.
I'm a happy user!
And finally since I'm a big MSBuild fan I might write an article in the future that handles the integration of NDepend with MSBuild/TFS/TeamCity/SharePoint...
Enjoy...
Making WCF RIA Services work in a DMZ/Multitier architecture using Application Request Routing
Introduction
In large companies / governments / ... most of the time the application architecture needs to follow a set of rules (focused on maintainability and security).
These could be rules like the following:
- The applications need to be developed following a Multitier architecture
- Each tier should be physically separated for security.
- The business logic tier is the only one that can connect to the data tier.
- The presentation tier only connects to the business logic tier.
- The presentation tier may not directly connect to the data tier.
- The presentation tier is located in a DMZ, other tiers are heavily secured.
- ...
Each project / company will have its own rules but the concept stays the same.
Here is an example of how this could be achieved in ASP.NET:

As you can see, for the data tier to be compromised one must first compromise the presentation and the business logic tier.
You can also assume that in most cases each physical tier is also protected by a firewall.
Default: Physical tiers in Silverlight + WCF RIA Services
When you're building an application in Silverlight with WCF RIA Services you'll get the following setup:

The setup is still a 3-tier achitecture, but the presentation tier runs on the client.
You could argue if the middle tier does or does not count as a presentation tier (since everything runs on the client) but let's say it does.
If you look at this from a security point of view it's less safer.
Once the webserver in the middle is compromised one has direct access to the data tier.
We could just add an extra tier containing some WCF Services that would be consumed by our WCF RIA Services but that would cause code duplication.
This would be an undesired side effect and thus we won't see this as a good solution to our problem.
Separate: An extra Web Application for WCF RIA Services
In my last post (Things you can do with WCF RIA Services and a regular .svc file) I described how you could separate the web application (hosting Silverlight) and the services. Resulting in the following setup:

As you can see here we're a step closer. Our services can live on one server and our web page (hosting the Silverlight application) on an other server. This does separate our tiers physically. But the problem is that Silverlight still requires a connection to WCF RIA Services directly.
In this setup our Business Logic Tier should be exposed to the internet / be in a DMZ / ... for our Silverlight client to access it.
And again, if this server is compromised one has direct access to the Data Tier!
Advanced: Using IIS Application Request Routing
For more information about ARR please visit: http://www.iis.net/download/ApplicationRequestRouting
We'll be using ARR (in combination with URL Rewrites) because it allows us to use IIS as a reverse proxy.
Using this reverse proxy we'll be able to achieve the following setup:

Follow these steps to install and configure IIS Application Request Routing.
A. Preparing the server(s)
- Make sure you have IIS 7 or IIS 7.5
- Download the Application Request Routing extension: x86 / x64
- Install the extension (it might install other extensions first)
- For testing purposes we'll simulate 2 servers on one machine.
To do this, open c:\windows\system32\drivers\etc\hosts with notepad.
127.0.0.1 presentationtier
127.0.0.1 logictier
We'll link these hostnames using host headers in IIS.
If you have 2 servers you can use for testing, please do (and you can skip this step).
But don't forget to install the WCF RIA Services Toolkit!
- Finally we'll configure the Application Request Routing.
In IIS Manager, click your server and go to Application Request Routing Cache:

Important note: If you work with multiple servers (and that's what you'll do in a real environment), you need to do this on your presentation tier (the ASP.NET website containing the Silverlight application).
- On the right select Server Proxy Settings and check the box Enable proxy.
B. Creating the site for the business logic tier
- In IIS, create a website called LogicSite

Note that the 'Host name' points to logictier under Binding.
This way we can simulate that this website is configured on the server logictier.
- Now go to Application Pools and open the LogicSite application pool.
Change the .NET Framework version to v4.0.

C. Provisioning the business logic tier site
Splitting up a Silverlight+RIA Services application requires some actions and you can read all about it in my last article.
We'll be using the solution from that article to get started right away. Note that this solution does not connect to a data tier, it just simulates this using a static list.
- Download the complete solution and extract it: Sandworks.Silverlight.nTier.zip (464.99 kb)
- Open the solution using Visual Studio
- Right click the project and select publish.

- Point the publish to the correct directory.

- Press Publish.
- Now visit http://logictier/Tasks.svc and your WCF RIA Service should be working correctly.

-
Now, create a file called clientaccesspolicy.xml in the root of this site containing the following XML (required for cross site access in Silverlight):
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="http://*" />
<domain uri="https://*" />
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
That does it. Our business logic tier (on a 'separate server') has been configured and is working.
D. Creating the site for the presentation tier (and reverse proxy)
- In IIS, create a site called PresentationSite

Note that the 'Host name' points to presentationtier under Binding.
This way we can simulate that this website is configured on the server presentationtier.
- Now go to Application Pools and open the LogicSite application pool.
Change the .NET Framework version to v4.0.
- For this application pool go to Advanced Settings and change the Idle-Time out to 0 minutes.
And finally go to Recycle... and clear the Regular time intervals (in minutes) checkbox.
E. Provisioning the presentation tier site
- Go back to Visual Studio, to the Sandworks.Silverlight.nTier.Client project.
- Open MainPage.xaml.cs
- Change both links you see there to http://logictier/Tasks.svc
- Rebuild the complete solution.
- Publish the Sandworks.Silverlight.nTier.Web site to our PresentationSite.

- Now, open the following link: http://presentationtier/Sandworks.Silverlight.nTier.ClientTestPage.aspx
- If everything goes well you should see a Silverlight application, and when you press the button Get all tasks you'll see this:

Now you've got a fictive server running the services and an other server running the actual web application hosting the Silverlight application.
The Silverlight application runs locally but still connects to the business logic tier. Now we created a setup as described in Separate (WCF RIA Services split in 2 servers).
Let's continue.
F. Configuring IIS Application Request Routing and IIS Rewrite
- Open the web.config of the PresentationSite (running on the presentation tier).
- Now add the following to the configuration file:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<rewrite>
<rules>
<rule name="Reverse Proxy to Business Logic Tier" stopProcessing="true">
<match url="^riaservices/(.*)" />
<action type="Rewrite" url="http://logictier/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
This will make sure all requests to the path riaservices are forwarded to our logictier server (containing the business logic tier).
- Now, visit the page: http://presentationtier/riaservices/Tasks.svc

And there you have it. Even tough we're visiting a page on the server presentationtier it's showing us content from the logictier server.
This means our Silverlight application no longer needs to talk to the logictier server. And thus, we don't need to expose our logictier server to the internet or put it in a DMZ.
Note 1: The clientaccesspolicy.xml file we placed in the LogicSite is no longer required.
Note 2: The system.serviceModel part in the config is very important. If it's missing you'll get the following error:
In your browser:
Server Error in '/' Application.
The resource cannot be found.
In EventViewer:
WebHost failed to process a request.
Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/27111447
Exception: System.Web.HttpException (0x80004005): The service '/riaservices/Tasks.svc' does not exist. ---> System.ServiceModel.EndpointNotFoundException: The service '/riaservices/Tasks.svc' does not exist.
G. The final result in our Silverlight application
- Go back to Visual Studio.
- Open MainPage.xaml.cs
- Change both urls to http://presentationtier/riaservices/Tasks.svc
- Rebuild the complete solution.
- Publish the Silverlight application like we did in E-5
- Check the web.config if it still contains the URL Rewrite configuration.
- Visit http://presentationtier/Sandworks.Silverlight.nTier.ClientTestPage.aspx
And we're done...
If you want you can start Fiddler and you'll see that our Silverlight application is only accessing our presentationtier server:

After a very long article this is what we've accomplished:

Our solution is ready for the enterprise!
Downloads:
Enjoy..