The other day I talked about doing Windows Authentication within a Windows Phone 7 application. I wanted to make it a simpler process so I created a helper class to do this:
public static class ClaimsAuthentication
{
static WSTrustClient client;
public static class Endpoints
{
public const string AdfsAuthentication = "/adfs/services/trust/13/usernamemixed";
}
public static void AuthenticateAsync(string endpoint,
IRequestCredentials credentials,
string appliesTo)
{
client = GetWSTrustClient(endpoint, credentials);
var rst = new RequestSecurityToken(WSTrust13Constants.KeyTypes.Bearer)
{
AppliesTo = new EndpointAddress(appliesTo)
};
client.IssueCompleted += client_IssueCompleted;
client.IssueAsync(rst);
}
private static void client_IssueCompleted(object sender, IssueCompletedEventArgs e)
{
client.IssueCompleted -= client_IssueCompleted;
if (e.Error == null)
Application.Current.SetPrincipal(e.Result);
IssueCompleted(sender, e);
}
public static event EventHandler<IssueCompletedEventArgs> IssueCompleted;
private static WSTrustClient GetWSTrustClient(string stsEndpoint,
IRequestCredentials credentials)
{
return new WSTrustClient(new WSTrustBindingUsernameMixed(),
new EndpointAddress(stsEndpoint), credentials);
}
}
You can call it like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
if (!CheckCredentials())
{
MessageBox.Show("Credentials Are Missing.");
return;
}
string endpoint = string.Format("https://{0}{1}", "adfs.example.com",
ClaimsAuthentication.Endpoints.AdfsAuthentication);
ClaimsAuthentication.IssueCompleted += new EventHandler
<IssueCompletedEventArgs>(ClaimsAuthenticationHelper_IssueCompleted);
ClaimsAuthentication.AuthenticateAsync(endpoint,
new UsernameCredentials(“user”, “pass”),
"urn:someapp:blah");
}
void ClaimsAuthenticationHelper_IssueCompleted(object sender, IssueCompletedEventArgs e)
{
if (e.Error != null)
{
showError(e.Error);
return;
}
DoSomething();
}