Yesterday I began learning WCF by porting an existing ASP.NET Web Service.
Creating the WCF service was very easy in itself. Approximately an hour after I created my first WCF Service Library project ever, I was already successfully testing my new WCF service in the WCF Test Client.
Now I would like to implement a simple authentication system, but still do not know how. For the sake of simplicity, say my Web Service has three operations: logging in, getting the length of the user’s name, and logging out. How do I complete the TODOs in the following code?
[ServiceContract]
public class MyService
{
[OperationContract(IsInitiating = true, IsTerminating = false)]
public bool Login(string userName, string password)
{
/* I have already implemented the function that validades
whether the user name and password are correct. */
if (ValidateLogin(userName, password))
{
/* TODO: Initiate a session */
return true;
}
else
return false;
}
[OperationContract(IsInitiating = false, IsTerminating = false)]
public int GetUserNameLength()
{
/*
TODO: How to validate whether the user has logged in?
How to obtain the name of the user that has logged in?
*/
int userNameLength = 42;
return userNameLength;
}
[OperationContract(IsInitiating = false, IsTerminating = true)]
public void Logout()
{
/* TODO: How to logout? */
}
}
NOTE: I am the enemy number one of gross hacks. Please lead me towards conceptually “clean” solutions, regardless of their complexity.
The approach you’re following may not be correct with WCF. Based on your approach above, the user is already authenticated as it’s able to invoke Login operation. Typically, User shouldn’t be allowed to invoke any operation until he/she is auhenticated, but in your approach that’s not the case.
Also, the sessions in WCF are client initiated, not server initiated. However, based on your approach they seems to be server initiated.
Here’re some resources which sheds more light on WCF Security,
http://msdn.microsoft.com/en-us/library/ms731925.aspx
Improve wcf security guidance – http://wcfsecurityguide.codeplex.com/
If you want to use Custom UserNamePassword validator, here is the link,
http://msdn.microsoft.com/en-us/library/aa702565.aspx
HTH,
Amit