Im trying to make a web request to sharepoint with client authorization but get 401 response code unauthorized

18 views Asked by At

Im trying to make a post request to create a folder inside a list item on my sharepoint site but for some reason i always get a 401 response even though my application has sharepoint permissions like: Sites.FullControl.All, Sites.Selected, User.Read.All. Is there something im missing do i need to add some type of permission in my sharepoint site or something else in azure ad? (i always get a valid token with the permissions given by my application)

```

  var clientId = "id";
  var tenantId = "id";
  var authority = $"https://login.microsoftonline.com/{tenantId}/";
  var clientSecret = "secret";

  var scopes = new string[] { "https://domain.sharepoint.com/.default" };

  var cca = ConfidentialClientApplicationBuilder.Create(clientId)
      .WithTenantId(tenantId)
      .WithAuthority(authority)
      .WithClientSecret(clientSecret)
      .Build();
  
  Console.WriteLine($"Requested scopes: {string.Join(", ", scopes)}");
  var authResult = await cca.AcquireTokenForClient(scopes).ExecuteAsync();

```
```

    using (var ctx = new ClientContext("https://domain.sharepoint.com/sites/sharepointsite"))
    {
        if (authResult != null && !string.IsNullOrEmpty(authResult.AccessToken))
        {
            try
            {
                ctx.ExecutingWebRequest += (sender, e) =>
                {
                    var token = "Bearer " + authResult.AccessToken;
                    e.WebRequestExecutor.WebRequest.Headers.Add("Authorization", token);
                    var request = e.WebRequestExecutor.WebRequest;
                    var requestUri = request.RequestUri;
                    var method = request.Method;

                    Console.WriteLine($"Outgoing Request: {method} {requestUri}");
                };

             }
             catch(Exception ex)
             {
                 Console.WriteLine(ex.Message);
             }

         }
         else
         {
             Console.WriteLine
             ("Failed to obtain a valid access token. Please re- authenticate.");
         }
         List documentLibrary = ctx.Web.Lists.GetByTitle("listname");

         var folderCreateInfo = new ListItemCreationInformation
         {
             UnderlyingObjectType = FileSystemObjectType.Folder,
             LeafName = "NewFolderName"
         };

         ListItem newFolder = documentLibrary.AddItem(folderCreateInfo);
         newFolder["Title"] = "New Folder";
         newFolder.Update();
         ctx.ExecuteQuery();
     }

    return Ok(AoNumber);

```
0

There are 0 answers