pINKmUNster
pINKmUNster

Reputation: 11

CSOM troubles with sharepoint online

I'm having some trouble with CSOM.

I'm trying to get the title of Sharepoint site, but unfortunately I'm getting this error => the remote server returned an error: (401) Unauthorized.

using (var context = GetClientContext("https://tenant.sharepoint.com/"))
 {
    context.Load(context.Web, p => p.Title);
    await context.ExecuteQueryAsync();
    Console.WriteLine($"Title: {context.Web.Title}");
  }

  public ClientContext GetClientContext(string targetUrl)
    {
       ClientContext clientContext = new ClientContext(targetUrl);
       clientContext.ExecutingWebRequest +=
        delegate (object oSender, WebRequestEventArgs webRequestEventArgs)
        {
           string token = GetToken();
            webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
                "Bearer " + token;
        };
         return clientContext   }



 public string GetToken()
        {
            IConfidentialClientApplication app;
            var instance = "https://login.microsoftonline.com/{0}";
            var tenant = "tenantId";
            var authority = String.Format(CultureInfo.InvariantCulture, instance, tenant);
            string[] scopes = new string[] { "https://tenant.sharepoint.com/.default" };

            app = ConfidentialClientApplicationBuilder
                .Create("clientId")
                .WithClientSecret("secretId")
                .WithAuthority(new Uri(authority))
                .Build();

            AuthenticationResult result = app.AcquireTokenForClient(scopes)
                .ExecuteAsync().GetAwaiter().GetResult();
            return result.AccessToken;
        }

This is the permissions for the appRegistration App Registration

But i can get it from a graph call

Upvotes: 1

Views: 1142

Answers (1)

Jerry
Jerry

Reputation: 3625

If want to use App Only permission in SharePoint Online CSOM, please register SharePoint Add-in instead of Azure AD's with this url:

https://tenant.sharepoint.com/_layouts/15/appregnew.aspx

enter image description here

Then set add-in permission using this xml in https:// TenantName-admin.sharepoint.com/_layouts/15/appinv.aspx:

<AppPermissionRequests AllowAppOnlyPolicy="true">    
    <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />    
</AppPermissionRequests>

enter image description here

Then install SharePointPnPCoreOnline Package using Nuget and call like this:

using OfficeDevPnP.Core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;

string siteUrl = "https://tenant.sharepoint.com/sites/demo";  
using (var cc = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, "[Your Client ID]", "[Your Client Secret]"))  
{  
    cc.Load(cc.Web, p => p.Title);  
    cc.ExecuteQuery();  
    Console.WriteLine(cc.Web.Title);  
};  

Here is a compeleted demo for your reference:

Connect To SharePoint Online Site With App Only Authentication

Upvotes: 1

Related Questions