Accessing SharePoint 2007 web services under forms based authentication

Posted on 6/1/2008 @ 12:49 AM in #SharePoint by | Feedback | 5948 views

SharePoint web services are asmx's, which is the equivalent of basicHttpBinding in WCF. I'm not a fan of the OOTB Web Services that come with SharePoint primarily because of 2 reasons

  • Let me decide what to expose over the web service API - i.e. let me author a contract. Not tie me down to OOTB web services that I may or may not need, and may or may not meet my need.
  • Like I said, being tied to only basicHttpBinding ~ which means hella inflexible and limiting. And because this is a plain vanilla asmx, you can't even swap the binding for anything else - That sucks!

But anyway, if you must, use an OOTB web service, and you're stuck with forms authentication (and thus your web services which insist on windows credentials are now not working), here is a way to get around it -

   1: // Authenticate   
   2: Authentication.Authentication auth = new Authentication.Authentication();   
   3: auth.CookieContainer = new CookieContainer(); 
   5: LoginResult result = auth.Login("username", "password");
   6: if (result.ErrorCode == LoginErrorCode.NoError)
   7: {
   8:     ExcelService es = new ExcelService();
   9:     CookieCollection cookies = auth.CookieContainer.GetCookies(new Uri(auth.Url));   
  10:     Cookie authCookie = cookies[result.CookieName];  
  11:     es.CookieContainer = new CookieContainer();
  12:     es.CookieContainer.Add(authCookie);
  13:     string targetWorkbookPath = "http://moss2007:81/Excel%20Sheets/Book1.xlsx";
  14:     Status[] outStatus;
  15:     string sessionId = 
  16:         es.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", out outStatus);
  17:     RangeCoordinates rc = new RangeCoordinates();
  18:     rc.Column = 1;
  19:     rc.Row = 1;
  20:     rc.Height = 4;
  21:     rc.Width = 2;
  22:     es.Calculate(sessionId, "Sheet1", rc);
  23:     object[] rangeResult = es.GetRange(sessionId, "Sheet1", rc, false, out outStatus);
  24:     System.Diagnostics.Debugger.Break();
  25: }

The above code illustrates this by using ExcelService.asmx (proxy instance is "es"). The "auth" variable is an instance of the Authentication.asmx, which is set to be accessible by anonymous users by default.

Of course, my recommendation is to just use WCF, but hey, if you must asmx it out .. go crazy!

Sound off but keep it civil:

Older comments..

On 6/30/2008 10:03:08 PM Share Pointless said ..
I can't even get the thing to sharepoint to run as advertised. Do people really use this dog?

On 12/9/2008 3:47:54 PM Oskar Austegard said ..
Just what I needed, thanks!

But Sahil, you really should refactor that method.