Validate SharePoint credentials using Client Object Model
Recently I wrote a simple console application in C# to modify certain parts of SharePoint sites.
Its job was to simply do the following:
- Collect data from a spreadsheet
- Modify SharePoint list based on the data
The program was intended to be used both as a standalone exe as well as from a web application. Another requirement was that the user of the program might not have SharePoint server installed.
This means that CSOM or Client-side Object Model needs to be used. Since the application was also supposed to be used as a standalone exe, I felt it would require validation of the user.
If the Sharepoint site is an intranet site or is on-premise, we can use the following piece of code.
private bool ValidateCredentials(string siteUrl, string username, string password)
{
ClientContext context = new ClientContext(siteUrl);
Web web = context.Web;
context.Credentials = new NetworkCredential(username, password, "domain");
try
{
context.Load(web);
context.ExecuteQuery();
return true;
}
catch(Exception e)
{
logger.Error(e, e.Message);
return false;
}
}
If the SharePoint site is on the internet or a Sharepoint Online site, we would need to use SecureString for wrapping the password.
private bool ValidateCredentials(string siteUrl, string username, string password)
{
ClientContext context = new ClientContext(siteUrl);
Web web = context.Web;
SecureString securePass = new SecureString();
foreach(char c in password.ToCharArray())
{
securePass.Append(c);
}
context.Credentials = new SharePointOnlineCredentials(username, securePass);
try
{
context.Load(web);
context.ExecuteQuery();
return true;
}
catch(Exception e)
{
logger.Error(e, e.Message);
return false;
}
}
Then we can use this method as follows:
if(!ValidateCredentials(spUrl, user, pass))
{
Exit(message: "Invalid Credentials");
}
Exit method is a handy method I added to provide exit points from several parts of the program.
private void Exit(string message = null, bool error = true)
{
if(message != null)
logger.Info(message);
if(error)
Environment.Exit(exitCode: 1)
else
Environment.Exit(exitCode: 0)
}