Monday, March 14, 2016

C# CSOM SharePoint authenticating Online and On-Premises

Recently I had the need to implement an authentication scenario for both SharePoint Online and SharePoint 2013. The authentication credentials for both scenarios are handled through different classes within different namespaces. First, let me share the two code samples for both.

ClientContext context = new ClientContext(siteUrl);
if (serviceType.Equals(ServiceTypes.Online))
   context.Credentials = new SharePointOnlineCredentials(emailAddress, password);
else if (serviceType.Equals(ServiceTypes.OnPremise))
   context.Credentials = new NetworkCredential(emailAddress, password);
   context.AuthenticationMode = ClientAuthenticationMode.Default;

As you can see here, I have defined two different credential types for both SharePoint Online and SharePoint On-Premises. 

Credentials property of the ClientContext class is a type of ICredentials interface. When it is defined like this, what all I need to do is pass the serviceType variable value that picks up the correct SharePoint site type. This could be a check box or a pair of radio buttons in the user interface that can be passed through to this layer. 

Once the context object is returned, you need to execute the executeQuery code block and then get the response as per whatever the properties expected to execute at the particular context.


  1. This got me out of a fix... thanks for posting :-)

  2. if I dont want use NetworkCredential(emailAddress, password); method, how can I do?