ASP.NET Meets CardSpace
Create a Rich Login Experience with IE 7 and Windows CardSpace
October 30, 2009
ASP.NET Under the Hood
LANGUAGES:VB.NET | C#
ASP.NETVERSIONS: 2.0
ASP.NET Meets CardSpace
Create a Rich Login Experience with IE 7 and WindowsCardSpace
By Michele Leroux Bustamante
Greetings ASP.NET architects and developers! Thisinstallment of ASP.NET Under the Hood explains how you can incorporate WindowsCardSpace into your authentication and authorization model.
Q. How can I create a CardSpace login experience for myusers, while still supporting traditional login and integrating this with my existingASP.NET membership and roles provider implementation?
A. Windows CardSpace is a client technology that is partof the .NET Framework 3.0. It is used for creating, managing, and sharingdigital identities in a secure and reliable manner. You can think of CardSpaceas an identity selector that securely stores informational claims about a user,making it easy for that same user to send this information to a trusted Website for authentication purposes. But it isn t just an identity selector CardSpace also makes it easier for users to identify the target site whereclaims are sent by authenticating the site and presenting its credentials foruser approval. In addition, users can review the claims that the site has demanded,and explicitly allow or disallow sending that information.
In this article I ll provide a brief introduction toCardSpace. Then I ll jump into the details for how you can enable your ASP.NET Websites for CardSpace as a login alternative. If you re new to CardSpace Irecommend you read the articles listed at http://wcs.netfx3.com/content/Articles.aspx.They ll help provide a foundation on the technology if you haven t exploredthis part of the .NET Framework 3.0 release yet, as well as get you up to speedon the specifics of CardSpace.
Information Cards and CardSpace: A Brief Tour
Cards refer to informational claims about a subject theuser that is to be given access to a Web site, Web service, or application(known as the Relying Party or RP). Claims might include your name, address,phone number, birth date, or any other information that might prove useful toidentify you. Different RPs may demand different sets of claims to authenticateand authorize callers.
Two types of information cards exist: personal cards andmanaged cards. Personal cards are self-issued cards that can be createddirectly in the CardSpace user interface. Managed cards are obtained from athird-party provider that is willing to assert that a set of claims really dorelate to you. CardSpace can store both types of cards, and creates or obtainsa security token containing the claims represented by those cards. That s theultimate goal to reliably create a security token that carries claims to identifythe user. The CardSpace user interface is accessible from the DigitalIdentities icon in the Control Panel, as shown in Figure 1.
Figure 1: You can create and managecards from Digital Identities in the Control Panel. This option is installedwith .NET Framework 3.0 on XP/SP2.
When you select Digital Identities it launches a hardenedCardSpace user interface where you can safely create personal cards, import andexport cards, protect cards with a pin, and perform other functions related tocard management.
Personal cards can contain a limited set of claims, mostof which are shown in Figure 2. You may create one or more personal cards basedon the type of information you share with different sites. For example, I havetwo cards one that contains my business e-mail, Web site, and relatedinformation, and another for my personal e-mail, Web log, and relatedinformation I might share. Personal cards work well for sites that I wouldnormally identify myself to with a username and password.
Figure 2: Creating a new personalcard with CardSpace.
When you create a self-issued card using CardSpace youactually create two things: the information card and a separate record withyour actual claims. This distinction is important because the actual informationcard does not contain the value of each claim. It is the responsibility of theidentity provider to store and protect the claims and issue tokens for thoseclaims based on a requested information card. In the case of self-issued cardsit just happens that a local identity provider exists inside the CardSpace environmentto do just that.
Managed cards may contain similar claims, but most likelyhave custom claims that are required by the card issuer. For example, a bankmay vouch for your account number and an airline may vouch for your frequentflyer number. The card issuer is entirely responsible for defining what claimstheir managed cards represent.
In the case of managed cards, my bank may issue a card forme to install in CardSpace, but the actual claims are stored remotely with thebank s identity provider. When a managed card is selected in the CardSpaceinterface, CardSpace makes a call to the managed identity provider to request atoken containing the required claims.
Identity Metasystem Participants and Browser Flow
Before I show you how to support CardSpace from yourASP.NET Web sites, I ll explain the flow between participants in the IdentityMetasystem and the Browser experience.
There are several key participants:
RelyingParty (RP). This is the target site that relies on a specific set of claimsto authenticate calls. In the context of this article, your ASP.NET Web sitewould be the RP.
Subject.This is the user described by a set of claims. For example, the user logging into your Web site.
IdentityProvider (IP). This party is responsible for generating a token thatincludes a set of claims describing the subject. They are the holder of thoseclaims, and must keep them secure. They must sign the token to prove that theyare the party that supplied the claims.
WindowsCardSpace. For Windows machines, CardSpace provides local storage for personaland managed information cards that represent a list of claims. As I mentioned,the card does not contain the actual claim values. For personal cards CardSpacesupplies a local IP that securely stores the actual claims. Thus, in caseswhere personal cards are supported by the target site, CardSpace acts as bothidentity selector and IP.
Figure 3 illustrates the interaction between eachparticipant, assuming personal cards (from CardSpace) are supported. Usersbrowse to a site that returns a login page supporting information cards. Whenthe user hits the login using CardSpace button, IE 7 hands off the request toCardSpace and waits for a signed and encrypted token to be returned.
The hardened CardSpace user interface appears presentingthe user with cards that satisfy the claims required by the target site. Ifthey previously have selected a card for the site, that card will behighlighted.
Figure 3: Interaction between user,browser, relying party, and CardSpace for self-issued cards.
After the user selects a card to send to the site,CardSpace sends a request to its local IP for a token containing the requiredclaims. The token is encrypted and signed by the local IP before CardSpace returnsit to the browser. Ultimately the token is posted to the RP via SSL.
The browser essentially calls GetToken on the CardSpaceAPI and waits for a signed and encrypted token to be returned. The entireexchange with the user for creating or managing their cards through theCardSpace user interface, for requesting the token from the IP, and forencrypting that token is heavily locked down. This is illustrated by the shadedarea in the diagram. No malicious code can easily be injected into thisexchange.
Let s Log In with CardSpace!
With that brief introduction to CardSpace, let s talkabout the requirements for invoking the CardSpace user interface from anASP.NET page. Here is a list of basic requirements:
1) YourWeb site must be SSL-enabled.
2) Arecent build of IE 7 is required for a browser experience with CardSpace.
3) YourASP.NET pages can use the
4) Whenthe security token is posted to the Web site, you are responsible forprocessing the claims inside the token and using them to authenticate calls.
Figure 4 illustrates the use of the
id="formCardSpaceLoginOBJECT" runat="server">
...
id="xmlTokenEncrypted"> value="urn:oasis:names:tc:SAML:1.0:assertion"/> value="http://schemas.microsoft.com/ws/2005/05/identity/issuer/self"/> value="http://schemas.microsoft.com/ws/2005/05/identity/claims/privatepersonalidentifier http://schemas.microsoft.com/ws/2005/05/identity/claims/emailaddress"/> ...
Figure 4: InvokingCardSpace with the
"http://www.identityselectors.org/2006/10"> ... id="formCardSpaceLoginXHTML" runat="server"> ... style="behavior:url(#default#informationCard)" issuer="http://schemas.microsoft.com/ws/2005/05/identity/issuer/self" tokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"> claims/privatepersonalidentifier" optional="false"/> claims/emailaddress" optional="false" /> ... ImageUrl="CardSpaceLogin.jpg" runat="server"/>
Figure 5: InvokingCardSpace with XHTML.
In both cases, the syntax of the
What format of security token does the Web site support?The
Which claims are required by the site forauthentication? In both cases, private personal identifier (PPID) and e-mailaddress claims are required. These are two of the standard set of claimssupported by self-issued cards.
Which identity provider (also called a securitytoken issuer) is trusted by the Web site? In both cases, self-issued tokens aresupported which implies the local CardSpace IP on Windows operating systems.For managed cards, a specific IP might have been required to issue signedtokens.
During postback you can access the issued SAML tokenthrough the Request object:
string token = Request.Form["xmlTokenEncrypted"] asstring;
Now the question is, what do you do with this token?
Processing the Token
The token string is in the form of an section. It is encrypted with the public key portion of the site s SSLcertificate. The code to decrypt it, therefore, must have access to the site s privatekey. Specifically, the ASP.NET account will need permissions to access theprivate key from the certificate store.
The code to decrypt the token is lengthy and a topic in andof itself, so I ll let you look at the code sample for those details. After thetoken is decrypted, what you ll find is that you are working with a SAML tokenthat has a set of claims inside. The claims are exactly those you requested (seeFigures 4 and 5). In this example the claims include a personal private identifier(PPID) and an e-mail address but there is a complete list of valid claims inthe CardSpace specification, and this can be extended for managed cards.
Once you have decrypted the token and verified that itincludes the claims you requested, it is time to authenticate.
Associating Cards with User Accounts
Users typically log in to a Web site with a username and apassword. Both the username and password are required to authenticate. A sitethat supports information cards is really stating that it supportsauthentication against a set of claims. As mentioned, those claims might be ausername, e-mail address, birth date, or some other information. But anyone candiscover this information and create a card with the same data, so before wecan authenticate these claims we need to know that the claims came from atrusted source. If it were a managed card, the token would be signed with thetrusted identity provider s private key. In the case of self-issued tokens, weneed to look at alternative ways to establish trust.
One approach is to have the card associated with the useraccount. That implies that the user must log in with their username andpassword prior to selecting a card to send to the site for the first time. Oncelogged in the user can select a card, which sends the security token to thesite. If the claims posted with the card include the user s e-mail address,this can be compared to the logged in user to verify the card matches the user.In addition, the personal private identifier of the card can be stored and usedto associate that specific card with the user s account:
MembershipUser user = Membership.GetUser
(this.User.Identity.Name);
if (user.Email == emailClaim)
{
user.Comment = ppidClaim;
Membership.UpdateUser(user);
}
The PPID is a special type of claim. This is a uniqueidentifier for a particular card sent to a particular site. Because a card canbe used for multiple sites, CardSpace generates a PPID for every site to which acard is sent. In short, the PPID represents the relationship between therelying party and the information card.
With the PPID of the card associated with their account, auser no longer has to provide their username and password to log in. When theylog in with the CardSpace option, instead of processing username and passwordcredentials, you can look up the user account by the e-mail address claim, andthen verify that the PPID of the posted token matches the PPID stored in theuser account (see Figure 6).
MembershipUser authenticatedUser = null;
MembershipUserCollection matchingUsers =
Membership.FindUsersByEmail(emailClaim);
if (matchingUsers.Count == 0)
{
// error
}
foreach (MembershipUser user in matchingUsers)
{
if (user.Comment ==ppidClaim)
{
authenticatedUser =user;
}
}
if (authenticatedUser == null)
{
//error
}
FormsAuthentication.RedirectFromLoginPage(emailClaim, false);
Figure 6: With thePPID of the card associated with their account, a user no longer has to providetheir username and password to log in.
The call to RedirectFromLoginPage handles generating anauthentication ticket for the user, and redirecting to the originally requestedpage just like the ASP.NET Login control would do with the username andpassword.
Creating a Dual Purpose Login Page
The code sample accompanying this article includes a loginpage that uses the ASP.NET Login control for traditional login, and the
First, I placed the
Next, I created a JavaScript function,SelectInformationCard, that would instantiate the CardSpace object, and put thevalue it returns into a hidden text field:
functionSelectInformationCard() { var infoCardObject=document.getElementById( "informationCards"); var hiddenToken =document.getElementById( "hiddenXmlToken"); hiddenToken.value =infoCardObject.value; }
Within the
tag I arranged the Login controland my CardSpace image button, along with the hidden text field (the latter twoare shown here):
ImageUrl="infocardlogin.jpg" /> name="hiddenXmlToken" /> Then I associated the client-side function,SelectInformationCard, to the ASP.NET ImageButton server control: if (!this.IsPostBack) { this.cardSpaceSubmit.Attributes.Add("onclick", "SelectInformationCard();"); } This last step makes it possible for the server control toinvoke a client-side function prior to completing the postback. Of course, thepostback includes the hidden text field, which will contain the encryptedtoken! Conclusion Allowing personal cards to be associated with a user slogin credentials can simplify their login experience significantly. Instead oftrying to remember their username and password every time they hit your sitethey can log in once, associate an information card with their account, and in thefuture go to CardSpace to log in with a few simple clicks. Hopefully thisarticle has provided you with enough of a teaser to inspire you to look atCardSpace for this purpose. The code for this article and related sample code is basedon the July CTP of .NET Framework 3.0. If you have additional questions on thisor other ASP.NET topics, drop me a line at [email protected].Thanks for reading! C# and VB.NET codeexamples are available for download. Michele LerouxBustamante is Chief Architect at IDesign Inc., Microsoft Regional Directorfor San Diego, Microsoft MVP for XML Web services, and a BEA TechnicalDirector. At IDesign Michele provides training, mentoring, and high-endarchitecture consulting services, specializing in scalable and secure .NETarchitecture design, globalization, Web services, and interoperability withJava platforms. She is a board member for the International Association ofSoftware Architects (IASA), a frequent conference presenter, conference chairof SD s Web Services track, and a frequently published author. She is currentlywriting a book for O Reilly on the Windows Communication Foundation. Reach herat http://www.idesign.net or http://www.dasblonde.net.
About the Author
You May Also Like