Connect to SharePoint site with MFA account using CSOM and PowerShell

We can use the CSOM script in PowerShell to work with SharePoint Online site, list, document library and files. Once we successfully installed the Microsoft SharePoint Online Client SDK components, we can use the below script to connect the SPO site with a normal user account (without MFA enabled).

#Add required references to SharePoint client assembly
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")

$userAccount = "[email protected]"
$password = "password"
$siteURL = "https://contoso.sharepoint.com/sites/site_name"

$secPwd = $(ConvertTo-SecureString $password -asplaintext -force) 
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) 
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userAccount,$secPwd) 
$ctx.Load($ctx.Web)
$ctx.ExecuteQuery()
 
Write-Host "Title: " $ctx.Web.Title -ForegroundColor Green
Write-Host "Description: " $ctx.Web.Description -ForegroundColor Green

The above script works fine with a normal user account without MFA enabled. If you tried the same script with MFA-enabled user credentials, then you will receive the below error message.

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

Connect SharePoint site with MFA enabled account using CSOM

We are going to use the OfficeDevPnP.Core assembly, there is a class AuthenticationManager which has the method GetWebLoginClientContext for creating a SharePointContext object with different authentication types. This method opens a pop-up to enter credentials and challenges for the second-factor authentication.

Install the SharePointPnPPowerShellOnline module by running the command  “Install-Module -Name SharePointPnPPowerShellOnline -Force” which installs the OfficeDevPnP.Core assembly.

#Add required references to OfficeDevPnP.Core and SharePoint client assembly
[System.Reflection.Assembly]::LoadFrom("C:\Program Files\WindowsPowerShell\Modules\SharePointPnPPowerShellOnline\3.29.2101.0\OfficeDevPnP.Core.dll") 
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")

$siteURL = "https://contoso.sharepoint.com/sites/siten_name"
 
$AuthenticationManager = new-object OfficeDevPnP.Core.AuthenticationManager
$ctx = $AuthenticationManager.GetWebLoginClientContext($siteURL)
$ctx.Load($ctx.Web)
$ctx.ExecuteQuery()
 
Write-Host "Title: " $ctx.Web.Title -ForegroundColor Green
Write-Host "Description: " $ctx.Web.Description -ForegroundColor Green

For more details, refer to this post: Connect to SharePoint site with MFA account in C# using CSOM

Advertisement