While using pnp.Framework in .Net 6 environment. I need authenticated client context to get Sharepoint Data but facing 403forbidden while running context.ExecuteQuery().
I want to use the clientId and clientSecret mode of authentication for getting data from my client to my environment but facing 403 forbidden request.
I registered App in the particular Azure Active Directory and added the following permissions.

using PnP.Framework;
using System.Security;
using System.Web;
namespace SharePointOnlinePNPProject
{
public class Program
{
static async Task Main(string[] args)
{
string appID= "appId/clientId";
string tenantId = "<tenantId>";
string clientSecret = "";
string queueTestingLink = "Input sharepoint url";
Uri site = new Uri("https://clientDomain.sharepoint.com");
string filePath= "/Shared Documents/Case Studies"
SecureString password = new SecureString();
foreach (char c in passcode)
{
password.AppendChar(c);
}
var scopes = new string[] { hostLink + ".default" };
try
{
using (var context = new AuthenticationManager().GetACSAppOnlyContext(site.OriginalString, appID, clientSecret))
{
var folder = context.Web.GetFolderByServerRelativeUrl(filePath);
context.Load(folder);
context.ExecuteQuery();
Console.WriteLine(folder.Name);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Use Sharepoint Admin Center to create App and use that App Id and Client secret to get authenticated client context. I was able to access data in the same code posted above.
Follow below steps to create Client Id and Secret for your organisations sharepoint tenant.

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

You will receive a page similar to the one below. Click “Trust it” and complete the process.
Use the Client Id and Client Secret we saved in first step for creating sharepoint pnp context and accessing the files in that organisation's tenant

For More Info : Please follow the below blog to configure app and get credentials. https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With