Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Sharepoint list using client Id and Client secret in asp.net C#

Currently, I'm able to access sharepoint list using user id and password as given below. But would like to understand on how can i access the list using Client Id and Client secret ?

string siteUrl = "https://xyz.sharepoint.com/sites/MyList/";
ClientContext clientContext = new ClientContext(siteUrl);
string username = ConfigurationManager.AppSettings["username"];
string password = ConfigurationManager.AppSettings["password"];
System.Security.SecureString passWord = new System.Security.SecureString();
foreach (char c in password.ToCharArray()) 
{    
    passWord.AppendChar(c);
}

clientContext.Credentials = new SharePointOnlineCredentials(username, passWord);
Web oWebsite = clientContext.Web;
ListCollection collList = oWebsite.Lists;
clientContext.Load(collList);
clientContext.ExecuteQuery();
like image 386
AKR Avatar asked Oct 21 '25 11:10

AKR


1 Answers

You can use the GetAppOnlyAuthenticatedContext method of PnP CSOM core.

After that you can use the code as below:

string siteUrl = "https://xyz.sharepoint.com/sites/MyList/";
string clientId = "<client-id>";
string clientSecret = "<client-secret>";

using (var clientContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl,clientId,clientSecret))
{       
    Web oWebsite = clientContext.Web;
    ListCollection collList = oWebsite.Lists;
    clientContext.Load(collList);
    clientContext.ExecuteQuery();
}

To add PnP CSOM core, go to your project references > manage nuget packages.

Add the SharePointPnPCoreOnline package.

enter image description here

References - Authenticate SharePoint using PnP Authentication Manager

Expose on public web your SharePoint Online information

like image 111
Gautam Sheth Avatar answered Oct 24 '25 00:10

Gautam Sheth



Donate For Us

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