0

I have the following code to connect to a site collection:-

            string s = "******8";
            SecureString passWord = new SecureString();
            foreach (var cc in s)
                passWord.AppendChar(cc);
            using (ClientContext context = new ClientContext("https://***.sharepoint.com/sites/***/"))

            {
                try
                {
                    context.Credentials = new SharePointOnlineCredentials("***@***.onmicrosoft.com", passWord);

                    context.Load(context.Web);
                    context.ExecuteQuery();

but on the context.ExecuteQuery(); i am getting The sign-in name or password does not match one in the Microsoft account system... although i am 100% sure that the username/password are correct.. but if i login to the UI using the username i will get a 2-factor authentication, so could this be the issue?

1

MFA/Modern Auth is the issue. You shouldn't be using a username/password as this will fail with modern auth and is a bad security practice. Instead, register a SharePoint Addin with the appropriate permission and leverage the Client ID/Secret.

https://docs.microsoft.com/sharepoint/dev/sp-add-ins/register-sharepoint-add-ins

0

For MFA Authentication, please download and install OfficeDevPnP.Core using Nuget:

enter image description here

static void Main(string[] args)  
{  
   string siteUrl = "https://<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);  
}   

Reference:

Using CSOM To Connect To A SharePoint Site With Multi Factor Authentication Enabled

Or you can create a app password and use this password instead of user password in the code snippet:

Manage app passwords for two-step verification

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.