Authenticate a C#/WPF app using CSOM and Client ID / Client Secret

I have developed a desktop application which accesses our company SharePoint Online site in order to utilize multiple lists. Currently, this app is using username/password credentials in order to obtain an AuthCookie, which is then used for every subsequent access. This AuthCookie will expire only when user changes their password, which will in turn prompt them to re-enter their new password and obtain the new AuthCookie.

Now, company IT has decided to deprecate this “legacy authentication” and switch to “modern authentication”. This, as a consequence, will prevent my application to access our site as username/password credentials are no longer accepted.

I am now looking into modern methods for authenticating with our SharePoint Online site and that lead me to using application-assigned Client ID and Client Secret.

First, how (if at all possible) can I authenticate my app using ClientID/ClientSecret? I would really appreciate a code snippet that (if possible) doesn’t rely on anything but CSOM. I have already learned about SharePointPnPOnlineCore package and confirmed that it works, but it depends on large number of other packages which I’d like to avoid having to distribute with my app. Additionally, once authenticated, any operation this app does on any list should be recorded as being in context of user running the app (CreatedBy/ModifiedBy columns should have the actual user running the app).

Second, if this is not possible using CSOM, I have also started exploring the use of MSAL.NET (which now seems to be the recommended method) but nothing I found so far has lead me to solving my problem explained above. Again, I’d really appreciate a code snippet which showcases the entire process of this type of authentication.

Finally, if using ClientID/ClientSecret is not the best choice, I would like to know what other options I have in order for my WPF application to properly authenticate and use CSOM.

Is it possible to create site collection after creating new content database in Sharepoint 2019 CSOM (C#)?

I’m working on SharePoint 2019 environment.

I have just created site collection programmatically (CSOM) using MSDN Link

However, I want to create a content database through CSOM and point this newly created Content DB for creating above new site collection.

Any help is much appreciated!

Configure App using CSOM c#

I am able to install/deploy an app to a sharepoint site using the code below

var appManager = new AppManager(context); var apps = appManager.GetAvailable(); var foundApp = apps.Where(a => a.Id == FeatureId).FirstOrDefault(); var installAppAsync = await appManager.InstallAsync(foundApp); 

However, one particular app needs to be tied to a specific document library when added to a site, how can I specify these parameters when installing the app?

How to add user to resource pool in sharepoint 2016 through CSOM C#?

Currently the sharepoint is setup in SharePoint permission mode. How do we add a new user to resource pool ? I’m able to add the user to a group using web.EnsureUser(“domainname//abc”). But the user doesn’t show up in the resource list until he access the sharepoint site. (PWA site)

I’m updating the owner of the project through my CSOM code.

Not getting All FieldValues in Powershell CSOM Sharepoint 2016

I have created powershell script to get File/Folder Size details of Sharepoint site.

However, I am not able to get all fieldValues of listItems. I am getting values for $ listItem.FieldValues[“FileRef”], $ listItem.FieldValues[“FileRef”] etc. whereas When I am trying $ listItem.FieldValues[“File_x0020_Size”] or $ listItem.FieldValues[“EncodedAbsUrl”], I am getting nothing. In CSOM, We can include required property in .Load, Not sure how to do it in Powershell. Thank You in Advance

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server  Extensions\ISAPI\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server  Extensions\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"  function retrieveListItems($  _web) {  try {     Write-host "Processing Web :"$  _web.URL     $  listCollection=$  _web.Lists;     $  ctx.Load($  listCollection);     $  ctx.ExecuteQuery();       foreach ($  list in $  listCollection)     {         $  ctx.Load($  list.RootFolder)         $  ctx.ExecuteQuery()         $  weburl= $  ctx.Web.ServerRelativeUrl         $  listUrl =$  ("{0}{1}" -f $  ctx.Web.Url.Replace($  ctx.Web.ServerRelativeUrl,''), $  list.RootFolder.ServerRelativeUrl)          if($  list.Hidden -ne "true" -and $  list.IsCatalog -ne "true" -and  $  list.BaseType -eq "DocumentLibrary")        {                        "{0}`t{1}`t{2}`t{3}`t{4}`t{5}`t{6}" -f $  list.Title, $  list.BaseType, $  list.RootFolder.ServerRelativeUrl,$  list.Title,"EnterSize", $  list.LastItemModifiedDate, $  list.ItemCount | Out-File -FilePath $  outputFile -Append               Write-host $  list.Title              $  listItems = $  list.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())             $  ctx.Load($  listItems);             $  ctx.ExecuteQuery();               foreach($  listItem in $  listItems)             {                 # $  sizeMB = "{0:N2}" -f (($  listitem["File_x0020_Size"])/1MB)                    #Here I am getting $  sizeMB=0                $  length=$  listItem.File.Length                  #Here I am getting $  length=0                 $  sizeN=$  listItem.FieldValues["File_x0020_Size"]                 #Here I am getting $  sizeN=0                 #check if ListItem is Folder or File                 if($  listItem["FSObjType"] -eq 1)                 {                                         "{0}`t{1}`t{2}`t{3}`t{4}`t{5}`t{6}" -f $  listItem["FileLeafRef"],'Folder',$  listItem["FileRef"],$  list.Title,$  sizeMB,$  listItem["Modified"],$  listItem["ItemChildCount"] | Out-File -FilePath $  outputFile -Append                 }                 else                 {                     "{0}`t{1}`t{2}`t{3}`t{4}`t{5}`t{6}" -f $  listItem["FileLeafRef"],'ListItem',$  listItem["FileRef"],$  list.Title,$  sizeMB,$  listItem["Modified"],$  listItem["ItemChildCount"] | Out-File -FilePath $  outputFile -Append                 }             }             }          }     if($  _web.Webs.Count -gt 0)      {          foreach($  subSite in $  _web.Webs)         {              $  ctx.Load($  subSite)            $  ctx.Load($  subSite.Webs)            $  ctx.ExecuteQuery()           $  size = GetWebSize($  subSite)            $  sizeMB = "{0:N2}" -f (($  size)/1MB)             "{0}`t{1}`t{2}`t{3}`t{4}`t{5}`t{6}" -f $  subSite.Title, 'Site', $  subSite.ServerRelative,'',$  sizeMB, $  subSite.LastItemModifiedDate, $  subSite.ItemCount | Out-File -FilePath $  outputFile -Append             retrieveListItems($  subSite)           }      }    $  ctx.Dispose() } catch {     $  _.Exception.Message     $  _ | Out-File -FilePath $  logFile -Append     exit }  }   function GetWebSize ($  web)       {   $  ctx.Load($  web.Folders)  $  ctx.ExecuteQuery()  [long]$  total = 0   foreach ($  folder in $  web.Folders) {       $  total += GetFolderSize -Folder $  folder   }           return $  total   }    function GetFolderSize ($  folder)   {   $  ctx.Load($  folder.Files)  $  ctx.Load($  folder.Folders)  $  ctx.ExecuteQuery();  [long]$  folderSize = 0    foreach ($  file in $  folder.Files) {      $  folderSize += $  file.Length;   }   foreach ($  fd in $  folder.Folders) {       $  folderSize += GetFolderSize -Folder $  fd   }   return $  folderSize   }     function generateSiteDataReports { try {      $  siteCollectionUrl= Read-Host -Prompt "Enter Site Collection URL"      $  Username =  Read-Host -Prompt "Enter userName: ";      $  password = Read-Host -Prompt "Enter password: " -AsSecureString ;              $  logFile = "$  PSScriptRoot\log.txt"      if(Test-Path $  logFile)     {         Remove-Item $  logFile     }      $  outputFile = "$  PSScriptRoot\SiteReport.csv"        # Remove existing output file     if(Test-Path $  outputFile)     {          Remove-Item $  outputFile     }       "{0}`t{1}`t{2}`t{3}`t{4}`t{5}`t{6}" -f "Title", "Object Type", "URL","ListName","Size", "Modified", "ItemCount" | Out-File -FilePath $  outputFile -Append     $  ctx=New-Object Microsoft.SharePoint.Client.ClientContext($  SiteCollectionUrl);     $  ctx.Credentials=New-Object System.Net.NetworkCredential($  Username, $  password);      $  ettkundWeb=$  ctx.Web     $  ctx.Load($  ettkundWeb)     $  ctx.Load($  ettkundWeb.Webs)     $  ctx.ExecuteQuery()      #Get Web Size    # $  size = GetWebSize($  ettkundWeb)       $  sizeMB = "{0:N2}" -f (($  size)/1MB)      # $  sizeGB = "{0:N2}" -f (($  size)/1GB)       "{0}`t{1}`t{2}`t{3}`t{4}`t{5}`t{6}" -f $  ettkundWeb.Title, 'Site', $  ettkundWeb.ServerRelativeUrl,'',"Enter FileSize", $  ettkundWeb.LastItemModifiedDate, $  subSite.ItemCount | Out-File -FilePath $  outputFile -Append       Write-host "Processing Web :"   $  ettkundWeb.URL     retrieveListItems($  ettkundWeb)  } catch {     $  _.Exception.Message     $  _ | Out-File -FilePath $  logFile -Append     exit }  }  generateSiteDataReports 

Get Sharepoint Permissions\Roles (custom) of a user from AD Group that is part of SP Group via CSOM

SharePoint 2013 + provider-hosted app.

User is part of AD group. AD group is part of Sharepoint group. Sharepoint group has custom security permissions assigned.

How do I check whether user has some custom permission?

The only way I could think of is to get user AD groups and retrieve permissions for these groups from SharePoint.

Update retention label and sensitivity label using CSOM

I’m trying to update the retention label and sensitivity label of a file in a SharePoint Online Document Library using CSOM.

I can update the Retention Label using the SetComplianceTag method and it works well. How do I update the sensitivity label? From what I could see online, I use the same method, but when I try and use the same method it just overwrites the retention label and the sensitivity label is unchanged.

Can anyone help?

Powershell SharePoint 2016 csom 403 forbidden error

So new to CSOM and wanting to know if I am coding something wrong or where I need to look to resolve this issue. Or even if there is a SharePoint 2016 security setting that needs to be enabled for CSOM to work.

Also note, authentication is via Claims Authentication on the site it doesn’t work on.



Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.Runtime.dll' Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.dll' $  SharePointSite = 'https://Sharepointsite/sites/sitename' $  SharePointGroup = 'Test Group' $  Creds = Get-Credential $  SPContext = New-Object Microsoft.SharePoint.Client.ClientContext("$  SharePointSite")   $  SPContext.Credentials = $  Creds $  SPGroups=$  SPContext.Web.SiteGroups  $  SPContext.Load($  spGroups)          $  SPGroups=$  SPGroups.GetByName("$  SharePointGroup") $  SPContext.Load($  SPGroups)         $  SPContext.ExecuteQuery()  $  SPGroups.Title 

On my test side which is http://sharepointsite/site/testsite it works fine and finds the group.

On the root of the test site, https://sharepointsite/ it works and returns no group found.

On another site under the same root http://sharepointsite/sites/othersite it fails with “Access denied” but I don’t have access to that site.

When I test to an https://sharepointsite2 or https://sharepointsite2/site/testsite I get “403 Forbidden” But I have full access to sharepointsite2 root, sites, and central admin.