User authentication with WP7 and SSL WCF Service

In my last post I described all steps that were needed to get a WP7 app connecting to a WCF Service using SSL and a self-signed certificate. What needs to be added to this solution is username/password authentication.

It turns out that this is pretty easy, after reading the post ‘Windows Phone 7 Data Access Strategies: Security’ by Andrea Boschin.

Step 1
Replace the custom binding of the service for a basic http binding:

<binding name="customBinding">
  <security mode="TransportWithMessageCredential" >
    <message clientCredentialType="UserName" />

Step 2
Add a custom username/password validator to the service:

public class MyPasswordValidator
    : UserNamePasswordValidator
  public override void Validate(string userName, string password)
    if (!AuthenticateUser(userName, password))
        throw new SecurityTokenValidationException("...");

  private bool AuthenticateUser(string userName, string password)
    return userName == "foo" && password == "bar";

And add it to the service behaviors:

    customUserNamePasswordValidatorType="WP7toWCFtestService.MyPasswordValidator, WP7toWCFtestService"
    userNamePasswordValidationMode="Custom" />

Step 3
Refresh the service reference in the WP7 app and change the code to access the service:

var ws = new Service1Client();
ws.ClientCredentials.UserName.UserName = "foo";
ws.ClientCredentials.UserName.Password = "bar";

ws.GetDataCompleted += ...

And voila, it is working!

Of course this is only a starting point, password should not be hard coded and you probably want to support multiple accounts. In the near future I will at least remove the username/password from the WP7 app. The user will have to supply them and they will be stored with encryption on the phone.

For my current app this single user solution is enough. When you want to support multiple users the ASP.NET Membership Framework (described in this post by Jon Simpson) can be a good option.

With the infrastructure secured it is finally time to write the actual app…