Request had insufficient authentication scopes. [403] c# - c#

I have two methods. One is to read data from Google Sheets and the other is to add a value to a single cell (But I actually want to append data to the last row but, I'm gonna start with just 1 record first). The btnLoadAttendance works perfectly but when I input something in the textbox1.Text, in the "UpdateValuesResponse result2 = update.Execute();" I get an error like so:
Request had insufficient authentication scopes. [403]
I found an answer here "Request had insufficient authentication scopes [403] when update cell spreadsheet" that says about commenting some lines. I tried commenting that line but it doesn't work for me. I still get the same error. Below is my code:
WORKING
private void btnLoadAttendance_Click(object sender, EventArgs e)
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
String spreadsheetId = "1b64mhUgdeRzGyJF4NfAPhkFY7br3c0o9rJ9mMnDBTR8";
String range = "Sheet1!A2:D";
SpreadsheetsResource.ValuesResource.GetRequest request =
service.Spreadsheets.Values.Get(spreadsheetId, range);
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
foreach (var x in values)
{
dgvAttendance.Rows.Add(x[0], x[1], x[2], x[3]);
}
}
else
{
MessageBox.Show("No data found.");
}
}
NOT WORKING
private void btnAddData_Click(object sender, System.EventArgs e)
{
string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
String spreadsheetId = "1b64mhUgdeRzGyJF4NfAPhkFY7br3c0o9rJ9mMnDBTR8/edit";
String range = "Sheet1!F5"; // update the F5 cell
//ValueRange response = request.Execute();
ValueRange valueRange = new ValueRange();
valueRange.MajorDimension = "COLUMNS"; //Rows or Columns
var oblist = new List<object>() { textBox1.Text };
valueRange.Values = new List<IList<object>> { oblist };
SpreadsheetsResource.ValuesResource.UpdateRequest update =
service.Spreadsheets.Values.Update(valueRange, spreadsheetId, range);
update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
UpdateValuesResponse result2 = update.Execute();
}
You help is very much appreciated.

Firstly delete the credentials files .credentials/sheets.googleapis.com-dotnet-quickstart.json stored at c:\user\Documents.credentials.
Change the scope variable used for reading cells from Google Spreadsheets from
string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
to
static string[] Scopes = { SheetsService.Scope.Spreadsheets };
After execution of code, API will authenticate again and then issue will be resolved.

I just needed to change:
string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
to
static string[] Scopes = { SheetsService.Scope.Spreadsheets };
and it took me all day!

Related

Problem loading MS Word docx file to Google Drive via .net nuget package API

we cannot anderstand why we upload docx-file via Google Drive API v3, it compleete success. But after we upload docx we try open file and cannot open it, thre is error in error
But when open our disk in browser (Google Chrome) and try upload docx again it opens fine, without any error.
Can you please tell what is wrong we made.
Code example
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-dotnet-quickstart.json
static string[] Scopes = { DriveService.Scope.DriveMetadata };
static string ApplicationName = "Drive API .NET Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
var clientSecrets = new ClientSecrets();
clientSecrets.ClientId = "";
clientSecrets.ClientSecret = "";
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
clientSecrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File();
// fileMetadata.Name = #"excel1.xlsx";
fileMetadata.Name = #"word22222.docx";
// fileMetadata.Name = #"present1.pptx";
// var fileStream = File.Open(#"c:\temp\present.pptx", FileMode.Open);
string fileId = string.Empty;
using (var fileStream = File.Open(#"c:\temp\word3.docx", FileMode.Open))
{
// var fileStream = File.Open(#"c:\temp\excel1.xlsx", FileMode.Open);
var fileUpload = service.Files.Create(fileMetadata, fileStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
// var fileUpload = service.Files.Create(fileMetadata, fileStream, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
fileUpload.Fields = "id";
// var fileUpload = service.Files.Create(fileMetadata);
// fileMetadata.MimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
// var fileUpload = service.Files.Create(fileMetadata, fileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
IUploadProgress progress = fileUpload.Upload();
if (progress.Status == UploadStatus.Failed)
{
Console.WriteLine(progress.Exception);
}
else
{
fileId = fileUpload.ResponseBody.Id;
Console.WriteLine("File ID: " + fileUpload.ResponseBody.Id);
}
}
Console.ReadKey();
var permission = new Google.Apis.Drive.v3.Data.Permission();
permission.Type = "anyone";
permission.Role = "writer";
permission.PermissionDetails = new List<PermissionDetailsData>();
var perm = service.Permissions.Create(permission, fileId);
perm.Execute();
Console.WriteLine("Premission created!");
Console.ReadKey();
Process.Start("explorer.exe", "https://docs.google.com/document/d/" + fileId + "/edit");
// Process.Start("explorer.exe", "https://docs.google.com/spreadsheets/d/" + fileId + "/edit");
// Process.Start("explorer.exe", "https://docs.google.com/presentation/d/" + fileId + "/edit");
Console.WriteLine("Redirected to browser!");
Console.ReadKey();
}
}
Consideration
According to the documentation and to my tests you cannot create a file with the metadata scope only.
Using this scope will result in a permission error. Please try to use a more restricted scope to perform this operation.
Insufficient Permission: Request had insufficient authentication scopes. [403]
Solution
You can use one of these:
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.appdata
In C# this translates in one of these statements:
static string[] Scopes = { DriveService.Scope.Drive };
// OR
static string[] Scopes = { DriveService.Scope.DriveAppdata };
// OR
static string[] Scopes = { DriveService.Scope.DriveFile };
Reference
Drive Files Create

Insufficient authentication scopes while write to spreadsheet from .NET

Trying to write to google sheets from .NET .
Got exception:
An unhandled exception of type 'Google.GoogleApiException' occurred in mscorlib.dll
Additional information: Google.Apis.Requests.RequestError
Request had insufficient authentication scopes. [403]
Errors [
Message[Request had insufficient authentication scopes.] Location[ - ] Reason[forbidden] Domain[global]
]
Analog function with read works fine. Credentials are created and google sheets API is enabled. I don't see any settings while create credentials regarding read/write. Spreadsheet is shared for everyone read/write. How to solve this problem?
static void UpdateEntry()
{
string spreadsheetId = "1IAD2okAWZD7anbt5L4ybgD2dxHBGmsY6IkNIWHBQkBM";
string ApplicationName = "myapp";
UserCredential credential;
using (var stream = new FileStream("credentials_1.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
String range = "new first sheet!A1";
//var range = "{sheet}!D543";
var valueRange = new ValueRange();
var oblist = new List<object>() { "updated" };
valueRange.Values = new List<IList<object>> { oblist };
var updateRequest = service.Spreadsheets.Values.Update(valueRange, spreadsheetId, range);
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
var appendReponse = updateRequest.Execute();
}

Google Sheets Api Request had insufficient authentication scopes

static string[] Scopes = { SheetsService.Scope.Spreadsheets };
static string ApplicationName = "Google Sheets API .NET Quickstart";
public String spreadsheetId;
SheetsService service;
public GoogleHandler(String id)
{
spreadsheetId = id;
UserCredential credential;
using (var stream =
new FileStream(#"bin\client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
This is my code for Google Sheets API. I have the static string[] Scopes = { SheetsService.Scope.Spreadsheets }; which were solutions I found for this problem, however that did not fix my problem. I have already deleted my .credentials folder and it does not prompt me to login.
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None
//new FileDataStore(credPath, true)
).Result;
I commented out that line and it fixed everything!

Creating new folder in Google Drive Fails with Insufficent Permission

I am trying to create new folder MY_FOLDER in Google Drive using Drive API, using the quick starter example and adding more to it as I read through the https://developers.google.com/drive/v3/web/quickstart/dotnet.
My scope is set as:
static string[] Scopes = { DriveService.Scope.DriveFile };
And I create service like this
private static void CreateService()
{
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.ReadWrite))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
As per example on this page [https://developers.google.com/drive/v3/web/folder], 2, I am creating new folder
var fileMetadata = new File()
{
Name = "MY_FOLDER",
MimeType = "application/vnd.google-apps.folder"
};
var request = driveService.Files.Create(fileMetadata);
request.Fields = "id";
var file = request.Execute();
Console.WriteLine("Folder ID: " + file.Id);
The error I get reads "Insufficient Permissions [403]"
UPDATE
I created credentials as described in same Google tutorial at https://developers.google.com/drive/v3/web/quickstart/dotnet

GoogleWebAuthorizationBroker.AuthorizeAsync throws an error

i was trying to create and run the sample project given in this link.
here is the code:
namespace GmailQuickstart
{
class Program
{
static string[] Scopes = { GmailService.Scope.GmailReadonly };
static string ApplicationName = "Gmail API Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
// List labels.
IList<Label> labels= request.Execute().Labels;
Console.WriteLine("Labels:");
if (labels != null && labels.Count > 0)
{
foreach (var labelItem in labels)
{
Console.WriteLine("{0}", labelItem.Name);
}
}
else
{
Console.WriteLine("No labels found.");
}
Console.Read();
}
}
}
after i have done everything stated in google's documentation, including issuing a secrets.json file for my application/product, i ran it.
It fails with an exception, containing a "An invalid argument was supplied" inner exception.
I have retried everything with a new acocunt given new api credentials, etc., and still same error occurs. what am i doing wrong?
Try this
ClientSecrets secrets = new ClientSecrets()
{
ClientId = CLIENT_ID,
ClientSecret = CLIENT_SECRET
};
var token = new TokenResponse { RefreshToken = REFRESH_TOKEN };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets
}),
"user",
token);
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "ApplicationName"
});

Categories

Resources