Connect to SharePoint Online using PowerShell with MFA (Multi-factor Authentication)

Requirement: Connect to SharePoint Online from PowerShell using multi-factor authentication.

PowerShell to Connect to SharePoint Online with MFA

Multi-factor authentication or two-factor authentication in Office 365 environments is often enabled as part of security hardening. Instead of typical user IDs and passwords, it adds an extra layer with SMS or phone calls to complete the authentication process. However, in SharePoint, when you enable MFA for the account you used to connect to SharePoint Online from PowerShell, it fails! A few extra steps need to be taken first before connecting successfully. In this guide, we will see how to connect to SharePoint Online using PowerShell with MFA, including the prerequisites and step-by-step instructions.

Here is the list of available options on how to connect to the SharePoint Online site through an account with Multi-Factor authentication enabled.

Create an App Password to Connect to SharePoint Online

Visit https://aka.ms/createapppassword to create an App password for your MFA-enabled account(s), Then connect to SharePoint Online with the App password! Here is the Connect-SPOService with MFA example:

#Admin Center URL of your SharePoint Online
$AdminSiteURL= "https://crescent-admin.sharepoint.com"
 
#Connect to SharePoint Online services
Connect-SPOService -url $AdminSiteURL -Credential (Get-Credential)

Ensure you enter your username and the App password for the credential prompt. This method works for SharePoint Online Management Shell, PnP PowerShell, or PowerShell – CSOM scripts. If needed, You can hard-code the user name and App password in the script to avoid the credentials prompt at run time:

#Variables for processing
$AdminCenterURL = "https://crescent-admin.sharepoint.com"

#User Name Password to connect 
$AdminUserName = "Salaudeen@crescent.com"
$AdminPassword = "xbcvvdjzedpcqdjkek" #App Password

#Prepare the Credentials
$SecurePassword = ConvertTo-SecureString $AdminPassword -AsPlainText -Force
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminUserName, $SecurePassword
 
#Connect to SharePoint Online tenant
Connect-SPOService -url $AdminCenterURL -Credential $Cred

The app Password method is ideal for unattended or scheduled scripts in the Windows task scheduler!

Connect SharePoint Online PowerShell with MFA (Multifactor Authentication) by Omitting the “Credential” Parameter

To connect with SharePoint Online from the SharePoint Online Management Shell with multifactor authentication enabled account, simply remove the -Credential parameter from the “Connect-SPOService” cmdlet because the Get-Credential cmdlet is not MFA aware!

Connect-SPOService -Url https://YourTenant-admin.sharepoint.com

Hit Enter, You’ll get a popup (PowerShell Window – which is MFA aware), and enter the credentials and code as you get in SharePoint login.

connect sharepoint online powershell with mfa

Once you are authenticated successfully, You can start using PowerShell cmdlets from the module in the PowerShell console or PowerShell ISE.

PnP PowerShell to Connect to SharePoint Online with MFA

To connect to SharePoint Online from the PnP PowerShell module using Connect-PnPOnline with MFA (multi-factor authentication), here are the options:

Option 1: Use the “-Interactive” switch if you want to connect to PnP Online with an account with Multi-factor authentication enabled. E.g.

#Site Variables
$SiteURL = "https://crescent.sharepoint.com"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive 

You’ll get a login prompt if you are not already connected with SharePoint Online. In the classic PnP PowerShell module, instead of “Interactive” use “useweblogin” switch for MFA login. Once connected, You can run any available PnP PowerShell Cmdlets with site collection admin permissions.

Option 2: Use the Client ID and Client Secret method to Connect to SharePoint Online with MFA
Create an AppID and Password as per my article: Connect-PnPOnline with Client ID and Client Secret then use the ClientId and ClientSecret credentials to connect to PnP.

#Site collection URL
$SiteURL = "https://crescent.sharepoint.com"
 
#Connect to SharePoint Online with AppId and AppSecret
Connect-PnPOnline -Url $SiteURL -ClientId "ca12s35f-7c48-4xbf-8238-760bc56bdeda" -ClientSecret "J8cFpsg/AS7KUL79fGX1ykbBVkd6q35030AamzAQO5gHj=" 

Once connected, you can start using PnP cmdlets for SharePoint Online. More on connecting to SharePoint Online through PnP PowerShell is here: How to Connect to SharePoint Online using PnP PowerShell?

Connect to CSOM PowerShell Script with MFA

To connect to SharePoint Online through CSOM PowerShell script with a Multi-factor authentication configured account, use this PowerShell:

$SiteURL = "https://crescent.sharepoint.com"

#Setup Authentication Manager
$AuthenticationManager = new-object OfficeDevPnP.Core.AuthenticationManager
$Ctx = $AuthenticationManager.GetWebLoginClientContext($SiteUrl)
$Ctx.Load($Ctx.Web)
$Ctx.ExecuteQuery()

Write-Host $Ctx.Web.Title

This method prompts for credentials and a two-factor authentication code! Please note, You need the classic version of PnP PowerShell module installed for this.

In conclusion, connecting to SharePoint Online using PowerShell with MFA is a great way to secure your data and protect against unauthorized access. By following the steps outlined in this guide, you should be able to connect to SharePoint Online with MFA enabled.

Typical Errors when Multi-Factor Authentication (MFA) is enabled:

If you try to connect to SharePoint Online with an MFA enabled account, You’ll get these error messages:
“Connect-SPOService : The sign-in name or password does not match one in the Microsoft account system.
At line:5 char:1
+ Connect-SPOService -url $AdminSiteURL -Credential (Get-Credential)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-SPOService], IdcrlException
    + FullyQualifiedErrorId : Microsoft.SharePoint.Client.IdcrlException,Microsoft.Online.SharePoint.PowerShell.ConnectSPOService”

Connect-SPOService : The sign-in name or password does not match one in the Microsoft account system.

PnP Connection failed with the error on MFA enabled Account:
“Connect-PnPOnline : The sign-in name or password does not match one in the Microsoft account system.
At line:6 char:1
+ Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-PnPOnline], IdcrlException
    + FullyQualifiedErrorId : Microsoft.SharePoint.Client.IdcrlException,SharePointPnP.PowerShell.Commands.Base.ConnectOnline”

Connect-PnPOnline : The sign-in name or password does not match one in the Microsoft account system.

CSOM PowerShell Script with Two Factor Authentication:
“Exception calling “ExecuteQuery” with “0” argument(s): “The sign-in name or password does not match one in the Microsoft account system.”
At line:23 char:1
+ $Ctx.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : IdcrlException”

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

Last but not least: Please note, Other than MFA, There could be other reasons for these errors. Such as Incorrect username or password, Account has been disabled or locked, Password expired, conditional access policies, legacy authentication is disabled, etc.

How do I Install SharePoint Online PowerShell Module?

To install the PowerShell Module for SharePoint Online, Open PowerShell as Administrator and enter: “Install-Module Microsoft.Online.SharePoint.PowerShell”.
More info: Install SharePoint Online PowerShell Module

How does PnP PowerShell connect to SharePoint Online?

Install the new PnP PowerShell module using: “Install-Module PnP.PowerShell” and then you can connect to the SharePoint site using the “Connect-PnPOnline” cmdlet.
More info: PnP PowerShell to connect to SharePoint Online

What is the difference between PowerShell and PnP PowerShell?

The PnP PowerShell module is an open-source and community-provided library that sits on top of PowerShell and offers 500+ cmdlets to work with the Microsoft 365 environment.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

15 thoughts on “Connect to SharePoint Online using PowerShell with MFA (Multi-factor Authentication)

  • I have disabled mfa for a service account and tested it , I am still getting account mismatch issue .

    I tried logging in with the account directly on different sites it’s loggin in. ..when i try to login with the same account as different user on windows powershell it’s giving error like incorrect password however the password is same.

    Reply
  • I am getting the following error – any help is appreciated:

    $Ctx.ExecuteQuery()
    | ~~~~~~~~~~~~~~~~~~~
    | Exception calling “ExecuteQuery” with “0” argument(s): “The remote server returned an error: (403) FORBIDDEN.”

    Reply
  • When i tried to connect with SPOservice i am getting the below error

    Connect-SPOService : Cannot contact web site ‘https://sdaagovae-admin.sharepoint.com/’ or the web site does not support SharePoint Online credentials. The response status code is ‘Unauthorized’. The response
    headers are ‘X-NetworkStatistics=27,4204800,4137,2920,1763869,4204800,716497, X-SharePointHealthScore=3, X-MSDAVEXT_Error=917656;
    Access+denied.+Before+opening+files+in+this+location%2c+you+must+first+browse+to+the+web+site+and+select+the+option+to+login+automatically., SPRequestGuid=3d8ca5a0-7043-6000-6f46-28d178e42ab6,
    request-id=3d8ca5a0-7043-6000-6f46-28d178e42ab6, MS-CV=oKWMPUNwAGBvRijReOQqtg.0, Strict-Transport-Security=max-age=31536000, SPRequestDuration=58, SPIisLatency=0, MicrosoftSharePointTeamServices=16.0.0.23522,
    X-Content-Type-Options=nosniff, X-MS-InvokeApp=1; RequireReadOnly, X-Cache=CONFIG_NOCACHE, X-MSEdge-Ref=Ref A: 233729A03EEB419B95DE7B58A0FD7F46 Ref B: DXB20EDGE0215 Ref C: 2023-04-03T10:08:32Z,
    Content-Length=0, Content-Type=text/plain; charset=utf-8, Date=Mon, 03 Apr 2023 10:08:32 GMT, P3P=CP=”ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI”,
    X-Powered-By=ASP.NET’.
    At line:13 char:1
    + Connect-SPOService -url $AdminCenterURL -Credential $Cred
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Connect-SPOService], NotSupportedException
    + FullyQualifiedErrorId : System.NotSupportedException,Microsoft.Online.SharePoint.PowerShell.ConnectSPOService

    Reply
  • Hi, I have followed all the above methods to log into SharePoint with MFA but nothing worked. Is there a way that I can get your help in identifying where the issue is, please???

    Reply
  • Hi Salaudeen, I am trying to use the Create App Password and Connect with App Password method to connect using pnp powershell module but I am getting Connect-PnPOnline : AADSTS50126: Error validating credentials due to invalid username or password error. I am not sure what I am doing wrong

    Reply
  • Restart PowerShell ISE.

    Reply
  • Hi Sir,

    I am trying above code to connect to MFA enabled site. I am able to connect site but when I am trying to create List , I am getting below error:

    Cannot convert argument “parameters”, with value: “Microsoft.SharePoint.Client.ListCreationInformation”, for “Add” to type “Microsoft.SharePoint.Client.ListCreationInformation”: “Ca
    nnot convert the “Microsoft.SharePoint.Client.ListCreationInformation” value of type “Microsoft.SharePoint.Client.ListCreationInformation” to type “Microsoft.SharePoint.Client.ListC
    reationInformation”.”

    Reply
  • Hi ,
    I have tried above code to create List with MFA enabled account. But I am getting issue while creating List. Please help me on this;

    Code:

    try {
    $SiteURL = “https://portal/sites/site1”
    $ListTitle = “NewList”
    [System.Reflection.Assembly]::LoadFrom(“C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll”)
    [System.Reflection.Assembly]::LoadFrom(“C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll”)
    [System.Reflection.Assembly]::LoadFrom(“C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.IdentityModel.Clients.ActiveDirectory.dll”)
    [System.Reflection.Assembly]::LoadFrom(“C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\OfficeDevPnP.Core.dll”)
    $authManager = new – object OfficeDevPnP.Core.AuthenticationManager;
    $Context = $authManager.GetWebLoginClientContext($SiteURL);#

    $Lists = $Context.Web.Lists
    $Context.Load($Lists)
    $Context.ExecuteQuery()
    $ListInfo = New – Object Microsoft.SharePoint.Client.ListCreationInformation
    $ListInfo.Title = $ListTitle
    $ListInfo.TemplateType = “100”
    $List = $Context.Web.Lists.Add($ListInfo)
    $List.Description = “new list description”
    $List.Update()
    $Context.ExecuteQuery()
    } catch {
    Write – Host – ForegroundColor Red ‘Error ‘, ‘:’
    $Error[0].ToString();
    sleep 10
    }

    Error:

    Cannot convert argument “parameters”, with value: “Microsoft.SharePoint.Client.ListCreationInformation”, for “Add” to type “Microsoft.SharePoint.Client.ListCreationInformation”: “Cannot convert the “Microsoft.SharePoint.Client.ListCreationInformation” value of type “Microsoft.SharePoint.Client.ListCreationInformation” to type “Microsoft.SharePoint.Client.ListC
    reationInformation”.”

    Please help me on this.

    Reply
  • …there is a typo or the parameter names are new! Correct is now:

    Connect-PnPOnline -Url <> -ClientId <> -ClientSecret <>

    Reply
  • Thanks Salaudeen. Your trick of creating app password help connecting via CSOM in PowerShell. One issue I noticed is with having App Password the SharePoint Online Admin pages were not loading. The loading spinner was displayed all the time for all admin pages. Call with Microsoft showed account conflict error. And after deleting the app password SPO Admin pages were loading fine. Just in case someone else face same issue.

    Reply
  • Salaudeen, you are the man! I cant thank you enough for all of your efforts with your blog. It has saved me so many times!

    Reply
  • Once you’ve connected via Connect-SPOService, how do you use a context to build up a query?

    Reply
    • The Connect-SPOService doesn’t get you the Context! You have to either use PnP or CSOM.

      Reply
  • Why am i seeing the same issues that you have 🙂 Thank you so much Rajack for detailing each and every minute details.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *