Last Updated: February 25, 2016
· arivazhagan

Authentication in Sharepoint 2013 using C# [CSOM client]

SharePoint authentication in c# is stratight forward like any other service authendication,
the code below shows the plain username and encrypted password will do the trick, These are the parameters i have,

  1. Site URL - Absolute full URL
  2. username - admin username [Obviuosly]
  3. password - Obviuosly

The way i am using the method as a validator for other methods and its more like a kick [Bootstrap] starter method. Lets split up the code,

  1. ClientContext - Which holds the entire tenant/domain informations
  2. Web - Holds the requested site details from the tenant
  3. SecureString - Holds encrypt the plain passWord for the server authendication
  4. SharePointOnlineCredentials - Its a authendication service

As the service call is async we are tracking by context.ExecuteQuery, If its authendicated user next like of code will run, else its throws the Exception that we will handle in catch.

public ClientContext Auth(String uname, String pwd,string siteURL) {
    ClientContext context = new ClientContext(siteURL);
    Web web = context.Web;
    SecureString passWord = new SecureString();
    foreach (char c in pwd.ToCharArray()) passWord.AppendChar(c);
    context.Credentials = new SharePointOnlineCredentials(username, passWord);
        Console.WriteLine("Olla! from " + web.Title + " site");
        return context;
    catch (Exception e) {
        Console.WriteLine("Something went wrong in Auth Module" + e);
        return null; 

So as we returning the context i can pass the context to other functions to utilize.