For one of my pet projects I am writing, I was contemplating how to integrate Windows Live Authentication with my standalone application, similar to Windows Live Messenger. Turns out, it is really easy! Below are the three steps that were needed for the integration:
- Download the Windows Live Client SDK from here and install it.
- Create a new project and add reference to Microsoft.WindowsLive.Id.Client assembly
- Write code similar to the one below:
using System;
using Microsoft.WindowsLive.Id.Client;
namespace WLAuthenticate
{
class Program
{
[STAThread]
static void Main(string[] args)
{
// Attempt user authentication
Console.WriteLine("Enter your passport email address: ");
string strPassportEmail = Console.ReadLine();
if (String.IsNullOrEmpty(strPassportEmail))
{
Console.WriteLine("Enter valid address!");
return;
}
// Got the details - attempt to authenticate
IdentityManager idMgr = null;
Identity curID = null;
// Create the identity manager
idMgr = IdentityManager.CreateInstance("OrganizationName;name@company.com;ClientAuthSample",
"Windows Live Client Authentication Sample App");
// and now create the user's identity from it..
curID = idMgr.CreateIdentity(strPassportEmail);
bool fAuthenticated = false;
if (curID != null)
{
if (curID.SavedCredentials == CredentialType.UserNameAndPassword)
{
// the credentials are persisted in local store and we can authenticate
fAuthenticated = curID.Authenticate(AuthenticationType.Silent);
}
else
{
// Credentials not available locally, so show the signin dialog...
curID = idMgr.CreateIdentity();
// This will prompt for credentials to authenticate...
fAuthenticated = curID.Authenticate();
}
if (fAuthenticated)
{
Console.WriteLine("Authenticated with Windows Live!");
Console.WriteLine("Your username is {0}", curID.UserName);
// Close the authentication
curID.CloseIdentityHandle();
}
}
}
}
}
Easy, isn't it :) ?
The only thing to be kept in mind is that if the passport authentication details are not persisted on the machine where authentication is attempted, then you will need to invoke Identity.Authenticate method without any arguments. This overload uses COM subsystem to display the Windows Live signin dialog to attempt authentication and requires the calling thread to be in STA mode and thus, tagged with STAThread attribute. Hence, I have set this attribute to the Main method above. Not setting this attribute will result in a ThreadStateException being raised.