Making an ASP.NET Website Claims Aware with the Windows Identity Foundation

Straight from Microsoft this is what the Windows Identity Foundation is:

Windows Identity Foundation helps .NET developers build claims-aware applications that externalize user authentication from the application, improving developer productivity, enhancing application security, and enabling interoperability. Developers can enjoy greater productivity, using a single simplified identity model based on claims. They can create more secure applications with a single user access model, reducing custom implementations and enabling end users to securely access applications via on-premises software as well as cloud services. Finally, they can enjoy greater flexibility in application development through built-in interoperability that allows users, applications, systems and other resources to communicate via claims.

In other words it is a method for centralizing user Identity information, very much like how the Windows Live and OpenID systems work.  The system is reasonably simple.  I have a Membership data store that contains user information.  I want (n) number of websites to use that membership store, EXCEPT I don’t want each application to have direct access to membership data such as passwords.  The way around it is through claims.

In order for this to work you need a central web application called a Secure Token Service (STS).  This application will do authentication and provide a set of available claims.  It will say “hey! I am able to give you the person’s email address, their username and the roles they belong to.”  Each of those pieces of information is a claim.  This message exists in the application’s Federation Metadata

So far you are probably saying “yeah, so what?”

What I haven’t mentioned is that every application (called a Relying Party) that uses this central application has one thing in common: each application doesn’t have to handle authentication – at all.  Each application passes off the authentication request to the central application and the central application does the hard work.  When you type in your username and password, you are typing it into the central application, not one of the many other applications.  Once the central application authenticates your credentials it POST’s the claims back to the other application.  A diagram might help:


Image borrowed from the Identity Training kit (

The key takeaway is that only one single application does authentication.  Everything else just redirects to it.  So lets actually see what it takes to authenticate against an STS (central application).  In future posts I will go into detail about how to create an STS as well as how to use Active Directory Federation Services, which is an STS that authenticates directly against (you guessed it) Active Directory.

First step is to install the Framework and SDK.



The SDK will install sample projects and add two Visual Studio menu items under the Tools menu.  Both menu items do essentially the same thing, the difference being that “Add STS Reference” pre-populates the wizard with the current web application’s data.

Once the SDK is installed start up Visual Studio as Administrator.  Create a new web application.  Next go to the Properties section and go into the Web section.  Change the Server Settings to use IIS.  You need to use IIS.  To install IIS on Windows 7 check out this post.


So far we haven’t done anything crazy.  We’ve just set a new application to use IIS for development.  Next we have some fun.  Let’s add the STS Reference.

To add the STS Reference go to Tools > Add Sts Reference… and fill out the initial screen:


Click next and it will prompt you about using an HTTPS connection.  For the sake of this we don’t need HTTPS so just continue.  The next screen asks us about where we get the STS Federation Metadata from.  In this case I already have an STS so I just paste in the URI:


Once it downloads the metadata it will ask if we want the Token that the STS sends back to be encrypted.  My recommendation is that we do, but for the sake of this we won’t.


As an aside: In order for the STS to encrypt the token it will use a public key to which our application (the Relying Party) will have the private key.  When we select a certificate it will stick that public key in the Relying Party’s own Federation Metadata file.  Anyway… When we click next we are given a list of available Claims the STS can give us:

There is nothing to edit here; it’s just informative.  Next we get a summary of what we just did:


We can optionally schedule a Windows task to download changes.

We’ve now just added a crap-load of information to the *.config file.  Actually, we really didn’t.  We just told ASP.NET to use the Microsoft.IdentityModel.Web.WSFederationAuthenticationModule to handle authentication requests and Microsoft.IdentityModel.Web.SessionAuthenticationModule to handle session management.  Everything else is just boiler-plate configuration.  So lets test this thing:

  1. Hit F5 – Compile compile compile compile compile… loads up http://localhost/WebApplication1
  2. Page automatically redirects to (notice the variables we’ve passed?)
  3. Type in our username and password…
  4. Redirect to http://localhost/WebApplication1
  5. Yellow Screen of Death

Wait.  What?  If you are running IIS 7.5 and .NET 4.0, ASP.NET will probably blow up.  This is because the data that was POST’ed back to us from the STS had funny characters in the values like angle brackets and stuff.  ASP.NET does not like this.  Rightfully so, Cross Site Scripting attacks suck.  To resolve this you have two choices:

  1. Add <httpRuntime requestValidationMode="2.0" /> to your web.config
  2. Use a proper RequestValidator that can handle responses from Token Services

For the sake of testing add <httpRuntime requestValidationMode="2.0" /> to the web.config and retry the test.  You should be redirected to http://localhost/WebApplication1 and no errors should occur.

Seems like a pointless exercise until you add a chunk of code to the default.aspx page. Add a GridView and then add this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.IdentityModel;
using System.IdentityModel.Claims;
using Microsoft.IdentityModel.Claims;

namespace WebApplication1
    public partial class _Default : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            IClaimsIdentity claimsIdentity = ((IClaimsPrincipal)(Thread.CurrentPrincipal)).Identities[0];

            GridView1.DataSource = claimsIdentity.Claims;

Rerun the test and you should get back some values.  I hope some light bulbs just turned on for some people :)

Getting the Data to the Phone

A few posts back I started talking about what it would take to create a new application for the new Windows Phone 7.  I’m not a fan of learning from trivial applications that don’t touch on the same technologies that I would be using in the real world, so I thought I would build a real application that someone can use.

Since this application uses a well known dataset I kind of get lucky because I already have my database schema, which is in a reasonably well designed way.  My first step is to get it to the Phone, so I will use WCF Data Services and an Entity Model.  I created the model and just imported the necessary tables.  I called this model RaceInfoModel.edmx.  The entities name is RaceInfoEntities  This is ridiculously simple to do.

The following step is to expose the model to the outside world through an XML format in a Data Service.  I created a WCF Data Service and made a few config changes:

using System.Data.Services;
using System.Data.Services.Common;
using System;

namespace RaceInfoDataService
    public class RaceInfo : DataService
{ public static void InitializeService(DataServiceConfiguration config) { if (config
== null) throw new ArgumentNullException("config"); config.UseVerboseErrors
= true; config.SetEntitySetAccessRule("*", EntitySetRights.AllRead); //config.SetEntitySetPageSize("*",
25); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
} } }

This too is reasonably simple.  Since it’s a web service, I can hit it from a web browser and I get a list of available datasets:


This isn’t a complete list of available items, just a subset.

At this point I can package everything up and stick it on a web server.  It could technically be ready for production if you were satisfied with not having any Access Control’s on reading the data.  In this case, lets say for arguments sake that I was able to convince the powers that be that everyone should be able to access it.  There isn’t anything confidential in the data, and we provide the data in other services anyway, so all is well.  Actually, that’s kind of how I would prefer it anyway.  Give me Data or Give me Death!

Now we create the Phone project.  You need to install the latest build of the dev tools, and you can get that here  Install it.  Then create the project.  You should see:


The next step is to make the Phone application actually able to use the data.  Here it gets tricky.  Or really, here it gets stupid.  (It better he fixed by RTM or else *shakes fist*)

For some reason, the Visual Studio 2010 Phone 7 project type doesn’t allow you to automatically import services.  You have to generate the service class manually.  It’s not that big a deal since my service won’t be changing all that much, but nevertheless it’s still a pain to regenerate it manually every time a change comes down the pipeline.  To generate the necessary class run this at a command prompt:

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

(Formatted to fit my site layout)

Include that file in the project and compile.

UPDATE: My bad, I had already installed the reference, so this won’t compile for most people.  The Windows Phone 7 runtime doesn’t have the System.Data namespace available that we need.  Therefore we need to install them…  They are still in development, so here is the CTP build

You should now have a compile-able project with service references that looks something like:


We have just connected our phone application to our database!  All told, it took me 10 minutes to do this.  Next up we start playing with the data.

Installing IIS 7.5 on Windows 7 from the Command Line

This is more of a place for me to store something I use fairly often, but can never remember off the top of my head.  This script, when run as administrator, will install all the features of IIS for developing on Windows 7.  Mind you, this is the prettified* version so it’s web-readable.

START /WAIT DISM /Online /Enable-Feature

*Interesting that “prettified” is a word according to Live Writer.

ADFS 2.0 Windows Service Not Starting on Server 2008

I’ve been working on getting a testable ADFS environment setup for evaluation and development.  Basically, because of laziness (and timeliness), I’m using Windows Virtual PC to host Server 2008 guests for testing.  I didn’t have the time to setup a fully working x64 environment, so I couldn’t go to R2.

One of the issues I’ve been running into is that the Windows Service won’t start properly.  Or rather, at all.  It’s running into a timing issue when running as Network Service, as its timing out while waiting for a network connection.  More Googling with Bing returned the fix for me from here.

In the file [C:\Program Files\Active Directory Federation Services 2.0\Microsoft.IdentityServer.Servicehost.exe.config] add this entry to it:

    <generatePublisherEvidence enabled="false"/> 

Other places have noted that this isn’t a problem on R2.  I haven’t tested this yet, so I don’t know if it’s true.

IIS 7 Certificate Request Completion breaking with &amp;ldquo;ASN1 bad tag value met 0x8009310b&amp;rdquo;

Only took a couple quick searches Googling with Bing, but in IIS 7 if you create a request for a certificate, create it by a CA and then complete the request, and find it blows up with this message box:

CertEnroll::CX509Enrollment::p_InstallResponse: ASN1 bad tag value met. 0x8009310b (ASN: 267)

All it means is that the CA that issued the certificate isn’t trusted on the server.  I came across this in a test environment I was building.  I had a Domain with CA Services, and a server that existed outside the domain.  I used the domain CA to create the certificate, but because the web server wasn’t part of the domain, it didn’t trust the CA.

My fix was to add the CA as a trusted Root Authority on the web server.

SQL Server 2008 R2 Launch Event &amp;ndash; Application Lifecycle Management

Unfortunately I will be unable to attend the ALM presentation later this afternoon, but luckily I was able to catch it in Montreal last week.

When I think of ALM, I think of the development lifecycle of an application – whether it be agile or waterfall or whatever floats your boat – that encompasses all parts of the process.  We’ve had tools over the years that help us manage each section or iteration of the process, but there was some obvious pieces missing.  What about the SQL?  Databases are essential to pretty much all applications that get developed nowadays, yet for a long time we didn’t have much in the way to help streamline and manage the processes of developing database pieces.

Enter ALM for SQL Server.  DBA’s are now given all the tools and resources developers have had for a while.  It’s now easier to manage Packaging and Deployment of Databases, better source control of SQL scripts, and something really cool: Database schema versioning.

I have a story: Sometime over the last couple years, a developer wrote a small little application that monitors changes to database schemas through triggers, and then sync’ed the changes with SVN.  This was pretty cool.  It allowed us to watch what changed when things went south.  Problem was, it wasn’t necessarily reliable, it relied on some internal pieces to be added to the database manually, and made finding changes through SVN tricky.

With ALM, versioning of databases happens before deployment.  Changes are stored in TFS, and its possible to rollback certain changes fairly easily.  Certain changes. :)

That’s pretty cool.

SQL Server 2008 R2 Launch &amp;ndash; PowerPivot

We just finished the SQL Server 2008 R2 Launch Keynote.  That’s quite a mouthful.  One of the problems I saw with this release was that not a lot of people knew what went into it.  R2 products are strange in that people just sort of assume they are nothing more than Service Pack releases.  Well, this isn't actually the case.

There were some really cool things shown in the keynote this morning.  PowerPivot being my all-time favorite.  Excel on Analysis Services steroids would be an apt description.  Analyzing huge sets of data within Excel was sort of tricky because you ran into a million row limit.  This was only half the problem though.  Performance was painful if you had that many rows in Excel -- sluggish at best.  PowerPivot helps change this dramatically.  The demo just shown pulled down 100,000,000 rows of data into Excel, filtered down to 19, and then filtered back up to the initial set -- all within a second.  That's pretty cool.

Just don't hit print.


WinFS has been puttering around my idle thoughts lately. 

Yep, weird.

Why is it still available on MSDN and TechNet subscriptions?

Food for thought.

Visual Studio Step Up Promotion...The Headache

A few months ago some friends of mine at Microsoft told me about a step-up promotion that was going on for the release of Visual Studio 2010.  If you purchased a license for Visual Studio 2008 through Volume Licensing, it would translate into the next version up for the 2010 version.  Seems fairly straightforward but here is the actual process:


So we upgraded our licenses to benefit from the step up.  Problem was, we couldn’t access any of the applications we were licensed to use (after RTM, obviously).  After a week or so of back and forth with Microsoft we finally got it squared away.  A lot of manual cajoling in the MSDN Sales system, I suspect, took place.  It turns out a lot of people were running into this issue.

Someone told me this issue got elevated to Steve B (not our specific issue, but the step-up issue in general).  I’m curious where things actually went wrong.  I suspect the workflow that was in place at the business level wasn’t in place at the technical level, so everything ended up becoming a manual process.  However, that is purely speculative.  Talk with Steve if you have questions.

In the end, everything worked out.  I got Visual Studio 2010 installed (which fricken rocks, btw), and my productivity will go up immensely once we get TFS deployed.  After of course, it has the necessary drop while I’m downloading and playing with the new MSDN subscription.

For those that are interested in the promotion, it’s still valid until the end of April.  Contact your account rep’s if you are interested.

A Launch Event For Visual Studio

About 10 minutes ago I was told to sit down and open my laptop.  The event is about start, and the place is extremely crowded.  Barnaby Jeans is on stage doing the usual intro.  Twitter, blog, twit tweet tweet tweet #vs2010.

Sean Graglia hits the stage.  Today VS2010 and .NET 4.0 were released.  It makes you a little nostalgic about the old days of development.  The way things were done, the way teams worked, the way we tested.  It’s changed quite a bit since a quarter century ago.  We used to be proud of a user interface that worked on an 80x24 printout.  Notsomuch anymore.

We now need a new way of doing things.  Visual Studio 2010 can help us with this.  Whether we want to deliver to conventional devices, or things like the phone, or even the cloud, Visual Studio can help us from inception to release.

So here we have Keith Yedlin from Corp up to now discuss the value of 2010.  First up is multi-CPU.  .NET 4.0 has created the ability to easily multi-thread processes for faster processing.  That’s actually pretty cool.  Multi-threading applications is for lack of a better word, terrible.  It’s hard to do natively, its hard to do in Managed code, and it’s even harder to figure out what’s going on after the fact.

Now, that brings up an interesting thought.  Debugging can be tricky.  Visual Studio 2010 has introduced something pretty awesome.  You can now create trace files for the debugger, and while that’s not all that interesting, you can load that back into the debugger from a remote PC and run through exactly what happened.  That is pretty fricken awesome.

Team Foundation Server

TFS was first released in 2005.  It was tricky to use, and the learning curve was fairly high.  Oh, and it was bloody expensive.  2010 has changed that entirely.  It’s now easier to use, easier to manage, and cost is much more reasonable (read: free version - FTW).  This can (and does) easily translate into faster time to market, more bug/test coverage, and overall better code.  Win-win-win.

More to come.