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:
1: <binding name="customBinding">
2: <security mode="TransportWithMessageCredential" >
3: <message clientCredentialType="UserName" />
Add a custom username/password validator to the service:
1: public class MyPasswordValidator
2: : UserNamePasswordValidator
4: public override void Validate(string userName, string password)
6: if (!AuthenticateUser(userName, password))
7: throw new SecurityTokenValidationException("...");
10: private bool AuthenticateUser(string userName, string password)
12: return userName == "foo"
13: && password == "bar";
And add it to the service behaviors:
3: customUserNamePasswordValidatorType="WP7toWCFtestService.MyPasswordValidator, WP7toWCFtestService"
4: userNamePasswordValidationMode="Custom" />
Refresh the service reference in the WP7 app and change the code to access the service:
1: var ws = new Service1Client();
2: ws.ClientCredentials.UserName.UserName = "foo";
3: ws.ClientCredentials.UserName.Password = "bar";
5: 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...