I'm been trying to do some custom code where I search on a Google Sheet file I owned for a specific string. Right now I have this working, I authenticated using a ApiKey and everything is working fine, BUT!!! I had to change the privacy of the file to "Public with url" to work. I think this is not quite right tho...
Then I moved to the next step, to iterate through all the files on a folder and its sub-folders, and search for that string on all the files, and here is where I'm having problems...
string ApplicationName = "My App Name";
string[] Scopes = { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
// Create Google Sheets API service.
var service = new DriveService(new BaseClientService.Initializer
{
ApplicationName = ApplicationName,
ApiKey = AppSettings.GetValue(AppSettings.API_KEY)
});
String folderId = "folder_id";
ChildrenResource.ListRequest request = service.Children.List(folderId);
do
{
try
{
ChildList children = request.Execute();
foreach (ChildReference child in children.Items)
{
Console.WriteLine("File Id: " + child.Id);
}
request.PageToken = children.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
request.PageToken = null;
}
} while (!String.IsNullOrEmpty(request.PageToken));
And I'm getting this error:
Google.Apis.Requests.RequestError
Login Required [401]
Errors [
Message[Login Required] Location[Authorization - header] Reason[required] Domain[global]
]
The same API Key is the one I'm using for the other chunk of code where I check if a single file has a string. The difference and where I think the problem is, is that the folder where I want to iterate the files is shared with me (I'm not the proprietary, but I have full access permissions to it). I also tried changing its privacy to Public without results.
Do you know what I'm getting this error? I have no clue.
SOLUTION:
string ApplicationName = "My App Name";
string[] Scopes = { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
ClientSecrets secrets = new ClientSecrets()
{
ClientId = ""MY_CLIENT_ID,
ClientSecret = "MY_CLIENT_SECRET"
};
var token = new TokenResponse
{
AccessToken = "MY_ACCESS_TOKEN",
RefreshToken = "MY_REFRESH_TOKEN"
};
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets
}),
"user",
token);
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = ApplicationName
});
return service;
All the tokens and keys, I got them from the OAuth2 Playground, is very easy to follow. Also thanks to this other guy answer.