Recently I was working on a project where a Windows Application needed to access Web Application via Web Services. Web Application was using FormsAuthentication. And Windows Application had to "log-in" to the Web Service in order to interact with it. So the solution I found to be working as desired is as follows.
My Web Service has a LogIn method:
public void LogIn(string username, string password)
{
if (!System.Web.Security.Membership.Provider.ValidateUser(username, password))
throw new System.Security.SecurityException("Enable to login");
System.Web.Security.FormsAuthentication.SetAuthCookie(username, true);
}
And my Windows Application has this code to call my Web Service:
private MyWebService myWebService;
private void Form1_Load(object sender, EventArgs e)
{
MyWebService myWebService = new MyWebService();
myWebService.CookieContainer = new System.Net.CookieContainer();
myWebService.LogIn(UsernameTextBox.Text, PasswordTextBox.Text);
}
Note that before calling LogIn methods, i'm setting CookieContainer property of the web service instance.
myWebService.CookieContainer = new System.Net.CookieContainer();
That's the trick to make it work. And it works like a charm.