0

I'm using CSOM for making REST API calls to a SharePoint list from a C# application. This needs credentials (of course), however I've found that it needs a username and a password in plain text. Something like code below:

using (ClientContext context = new ClientContext("https://site.sharepoint.com"))
{
    context.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication; 
    context.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo("[email protected]", "P@ssw0rd");
    // Rest of the code
    context.ExecuteQuery(); // <-- error on this line
}

I've two issues with this code:

  1. However I use the correct credentials, it's given me this error on the marked line:

    The user's login name or password is not valid.

  2. Security. It's not secure to add the credentials in plain text in the code.

I've also tried code below, but I get a 403 response (also with the correct credentials) and it's not secure too.

using (ClientContext context = new ClientContext("https://site.sharepoint.com"))
{
    context.Credentials = new NetworkCredential("[email protected]", "P@ssw0rd");
    // Rest of the code
    context.ExecuteQuery(); // <-- error on this line
}

In the header stand this:

Access denied. Before opening files in this location: you must first browse to the web site and select the option to login automatically.

How can I solve this, especially the second issue?

1 Answer 1

1

Sharepoint Online requires SecureString object as password. You can do something like this:

 SecureString se = new SecureString();
 foreach (var cc in password)
 {
     se.AppendChar(cc);
 }
 var cre = new SharePointOnlineCredentials("[email protected]", se);
 using (ClientContext context = new ClientContext("https://site.sharepoint.com"))
 {
     context.Credentials = cre;
     // Rest of the code
     context.ExecuteQuery();
 }

To solve the plain text password problem, you can store it in the Windows Credential Manager then retrieve it using this Library CredentialManager

2
  • Yes you can do that but SecureString requires a plain text password too. Mar 17, 2019 at 12:15
  • That's why I recommend CredentialManager class which returns SharePointOnlineCredential object var credential = CredentialManager.GetSharePointOnlineCredential(name);
    – Jack Le
    Mar 17, 2019 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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