Question

When connecting to online site we have Microsoft authentication call to our phones and we will enter our pin for authenticating.Then only we can access the site.

But in csom code when conencting to site I am getting the error:

"Exception calling "ExecuteQuery" with "0" argument(s): "The sign-in name or password does not match one in the Microsoft account system.".

Here is my code:

$ctx=New-Object Microsoft.Sharepoint.Client.ClientContext($siteCollUrl)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $securePassword)
$web=$ctx.Web
$ctx.Load($web)
$ctx.ExecuteQuery()

How can I access the site if MFA is enabled through csom pwoershell. please suggest.

Was it helpful?

Solution

If you are using PnP powershell you can use the below code,

When using the Connect-PnPOnline cmdlet without any additional authentication parameters, we are prompted for username and password, which will not work if multi-factor authentication is enabled. We can use the following switch to show a web login for authentication which handles MFA.

Connect-PnPOnline -Url $siteUrl –UseWebLogin

From CSOM:

static void Main(string[] args) 
{ 
   string siteUrl = "https://< Jump tenant-name>.sharepoint.com/sites/contosoteam"; 
   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); 
}

Source

OTHER TIPS

You can use SharePoint Online Management Shell to connect with multi-factor authentication (MFA) SharePoint Site.

Follow below documentation:

To connect with multi-factor authentication (MFA).

OR

Using UseWebLogin:

Connect-PnPOnline -Url $siteUrl –UseWebLogin

enter image description here

OR

Using App Password:

Also, you can use App password in place of normal password to login easily.

I am using App Password for authentication in PowerShell as well as SharePoint Designer and it works well.

Create an app password for Office 365.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top