I have a SharePoint Hosted App that I want to deploy to a SPOnline site and trust the App programmatically using CSOM. Idea is to mimic manual installation completely. I tried the below threads and the App starts appearing in the site content, however, it is not trusted. The CSOM code is running with credentials of a Tenant Administrator and App requires manage permissions on the site:
How to add a custom app to a SharePoint Online site programmatically
Deploying and Installing Sharepoint apps into App catalog using CSOM
There is a remote event receiver for App Install event and it is getting triggered:
using (ClientContext clientContext = tokenObj.CreateAppEventClientContext(properties, useAppWeb: false))
{
try
{
if (clientContext != null)
{
clientContext.Load(clientContext.Web);
clientContext.Load(clientContext.Web.CurrentUser);
clientContext.ExecuteQuery();
However, last line throws exception:
ServerUnauthorizedAccessException: Access denied. You do not have permission to perform this action or access this resource.
Please let me know if it is possible in SPOnline to install an App and trust it so that it is fully usable as manually installed App.
Update 1: Changed App manifest to remove remote event receiver endpoint for AppInstalled event. Now the App gets installed but it still doesn't have permissions. If I trust the App again manually from the App permissions page then everything starts working.