Access Sharepoint list using client Id and Client

2020-03-08 05:49发布

问题:

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();

回答1:

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.

References - Authenticate SharePoint using PnP Authentication Manager

Expose on public web your SharePoint Online information