Hello SharePointers,
Today we are going to discuss How to connect MFA enabled SharePoint site using CSOM in SharePoint Online.
Introduction
Usually, we write new scripts and utilities to perform certain tasks or to automate the business process in SharePoint Online.
We often implement some tools which always run with particular credentials (usually SharePoint administrator or Site Collection administrator) which have the higher privileges. In this process we need to store the credentials at a Central credentials Manager.
For a simple process, we often pass credentials in a code (hard code) else them in configuration files such as app.config or web.config.
By this way of authentication doesn’t work if Multi-Factor Authentication is enabled for that specific site. How to connect to a SharePoint site with MFA enabled?
Here the SharePoint PnP comes and make our life easier. Lets see some code snippets below to connect MFA enabled SharePoint site using CSOM.
Connect so site with MFA using CSOM
Below is the sample code using CSOM within a console app. The same code can be used to build windows forms or some other applications using CSOM.
Within a namespace called OfficeDevPnP.Core, there is an Authentication Manager class which has many helper methods to create SharePointContext object with different authentication methods.
In the below code, we are going to use the method GetWebLoginClientContext(SiteUrl). This will work for almost all types of authentication scenarios.
This method will pop up a dialog to enter a UserName and Password for the site. It will ask for an authentication token.
Below are the steps need to follow.
STEP 1: Install “SharePointPnPCoreOnline” NuGet package to the visual studio solution.
STEP 2: Copy and Paste below code into Program.cs file. (change URL attribute with your actual URL).
static void Main(string[] args)
{
string siteUrl = "https://<tenant-name>.sharepoint.com/sites/MFADemo";
var authManager = new OfficeDevPnP.Core.AuthenticationManager();
// This method calls a pop up window with the login page and it also prompts
// for the multi factor authentication code.
ClientContext ctx = authManager.GetWebLoginClientContext(siteUrl);
// The obtained ClientContext object can be used to connect to the SharePoint site.
Web web = ctx.Web;
ctx.Load(web, w => w.Title);
ctx.ExecuteQuery();
Console.WriteLine("You have connected to {0} site, with Multi Factor Authentication enabled!!", web.Title);
}
after successfully done the code, Build a Solution and Run it.
STEP 3: The running solution will prompt you to a dialog box for the credentials. Enter your credentials and provide an authentication token.
Yes, and all set. run your code and you will see output as below.
Our other posts are below.
4 thoughts on “Connect MFA enabled SharePoint site using CSOM”