1

I am trying to connect to a Sharepoint site which I can open & navigate in a browser, so I do have permissions. But in my .NET Framework 4.7.2 Console app, I am getting "401 unauthorized". What am I missing? I am using the "Microsoft.SharePoint.Client.Online.CSOM" nuget package, not sure if that's the right one, but only there I had the "SharePointOnlineCredentials" which other posts recommend to use.

var siteUrl = "https://mycompany.sharepoint.com";
var context = new ClientContext(siteUrl);
var securePassword = new NetworkCredential("", "mypw").SecurePassword;
context.Credentials = new SharePointOnlineCredentials("myusername@mydomain", securePassword);
var web = context.Web;

context.Load(web);
context.ExecuteQuery(); // 401 UNAUTHORIZED

When I am using the "Microsoft.SharePointOnline.CSOM" package instead, I am getting this error:

"Cannot contact web site 'https://mycompany.sharepoint.com/' or the web site does not support SharePoint Online credentials. The response status code is 'Unauthorized'. The response headers are 'X-SharePointHealthScore=0, 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"

Until now, I couldn't find anything that helped.

Do I need to register the app in Azure AD or is that only needed for .NET Standard?

IngoB
  • 2,552
  • 1
  • 20
  • 35
  • What have you tried so far to find a solution? – Andrew H Oct 01 '21 at 16:15
  • I tried it with the full url to a sub folder containing the documents I need to query, but I also got "unauthorized". I tried the "Microsoft.SharePointOnline.CSOM" API but that doesn't contain the SharePointOnlineCredentials class. I referenced the Microsoft.Online.Sharepoint.Client.Tenant.dll. I set context.AuthenticationMode = ClientAuthenticationMode.Default, with no success. – IngoB Oct 01 '21 at 16:27
  • You should update your question with the steps you've taken to try to solve the problem so answerers can know what you've already tried. – Andrew H Oct 01 '21 at 16:28

1 Answers1

1

It's now working with the "PnP.Framework" nuget package and this code:

var credentials = new System.Net.NetworkCredential("myusername@mydomain", "mypw");
var authManager = new AuthenticationManager(credentials.UserName, credentials.SecurePassword);
using (var context = authManager.GetContext("https://mycompany.sharepoint.com"))
{
    var web = context.Web;
    context.Load(web, w => w.Id, w => w.Title, w => w.Url);
    context.ExecuteQuery();
}
IngoB
  • 2,552
  • 1
  • 20
  • 35