Using the Client Object Model with a Forms Based Auth Site in SharePoint 2010

One of the questions I’ve seen a few times since my “mega-posting” on the client object model, is how to use it with a SharePoint site that is secured with forms based authentication.  There are actually a couple of ways you could do this.  The more complicated approach that I won’t describe in great detail here is to use the Authentication web service, similar to how I described for SharePoint 2007 in my Forms Based Authentication whitepaper part 2.  Fortunately though, the folks designing the client OM baked in a much simpler way to do this.  The ClientContext class includes an AuthenticationMode and FormsAuthenticationLoginInfo properties to help you manage this.

Here’s an example of using them to get a list of all the lists in the site.  Note this doesn’t follow the advice that I gave in one of the other client OM posts about specifying the properties you want returned, but I just wanted a quick and simple example to demonstrate:

ClientContext ctx = new ClientContext(someSiteUrl);
ctx.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
ctx.FormsAuthenticationLoginInfo = new
                    FormsAuthenticationLoginInfo(myUserName, myUserPwd);

//get the web
Web w = ctx.Web;

//LOAD LISTS WITH ALL PROPERTIES
var lists = ctx.LoadQuery(w.Lists);

//execute the query
ctx.ExecuteQuery();

foreach (List theList in lists)
{
        //do something here

}

P.S. As a side note, are you all noticing how much the formatting in these posts STINKS since they upgraded the site?  How unpleasant…