Tuesday, January 3, 2017

Retrieving Data from a Multi-Authentication Site by Using the Client Object Model and Web Services in SharePoint 2010

link : https://msdn.microsoft.com/en-us/library/office/hh124553(v=office.14).aspx


In this article, I am covering only the most common parts of how to retrieve data from a multi-authentication site by using the client object model and web services; there are multiple twists that can be added. The scenario is to retrieve data from a SharePoint site that is using multiple authentication providers. In this scenario, assume that one of the authentication providers is Windows claims and the other authentication provider is anything else—it could be forms-based authentication or a SAML authentication provider. Often you want to retrieve data from such a site by using either the client object model or SharePoint web services, but you want to use Windows authentication to do so. The problem up to this point has always been that even when you set your Windows credentials on the request, you still get an access denied error when requesting the data.
The resolution to this problem is that, if you want to programmatically access a SharePoint site that uses multiple authentication providers by using a set of Windows credentials, you must add an additional header to your request. The header name must be X-FORMS_BASED_AUTH_ACCEPTED and the value must be f. Adding this header can be a bit complicated for these two common scenarios (that is, using the client object model or web services). The rest of this article explains how to do that and gives some sample code. If you are using the client object model, you must add an event handler for the ExecutingWebRequest event. The following is a code example.



//Create the client context.
ClientContext ctx = new ClientContext(MixedUrlTxt.Text);
//Configure the handler that will add the header.
ctx.ExecutingWebRequest +=
new EventHandler(ctx_MixedAuthRequest);
//Set the Windows credentials.
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;
//Get the web.
Web w = ctx.Web;
//Load lists with all properties. 
var lists = ctx.LoadQuery(w.Lists);
//Execute the query.
ctx.ExecuteQuery();
//Enumerate the results.
foreach (List theList in lists)
{
//Do something with each list.
}


void ctx_MixedAuthRequest(object sender, WebRequestEventArgs e)
{
try
{
//Add the header that tells SharePoint to use Windows authentication.
e.WebRequestExecutor.RequestHeaders.Add(
"X-FORMS_BASED_AUTH_ACCEPTED", "f");
}
catch (Exception ex)
{
MessageBox.Show("Error setting authentication header: " + ex.Message);
}
}

No comments: