Locally saved credentials google drive api 3 - c#

I'm creating a desktop app in C#. The first time i started my app everything went fine they asked me to log-in and the permission. Now i can't log-in with another account since they saved everything locally.I tried deleting the file at ~/.credentials/drive-dotnet-quickstart.json and yes it worked but again only once they resaved the credentials but somewhere else and i can't find where. I want to be able to log-in from different account and since i also need to change the scope for permission issue i have to delete the previously saved credentials. There is how i log-in.
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/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
Console.WriteLine(credential.ToString());
service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
How can i delete the saved credentials ?
How can i disable the credentials saving mechanism ?
Thank you.

You can "Log out" by calling await credential.RevokeTokenAsync() or use another userID in GoogleWebAuthorizationBroker.AuthorizeAsync
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecretsStream = stream,
Scopes = new[] { DriveService.Scope.DriveReadonly },
DataStore = new FileDataStore(credPath, true)
});
credential = new UserCredential(flow, userId,
await flow.LoadTokenAsync(userId, CancellationToken.None)
);
bool res = await credential.RevokeTokenAsync(CancellationToken.None);
//credential = await GoogleWebAuthorizationBroker
// .AuthorizeAsync(
// stream,
// new[] { DriveService.Scope.DriveReadonly },
// userId,
// CancellationToken.None,
// new FileDataStore("oauth/drive"))
// ;
//Console.WriteLine("Credential file saved");
}
To check if credential is existed in local
await new FileDataStore(credPath, true).GetAsync<TokenResponse>(userId) != null
//or
await flow.LoadTokenAsync(userId, CancellationToken.None) != null

Just delete the token file which in "credPath" folder

Related

get all playlist of an user from YouTube. working in api explorer but not in c#

I wanna get all playlists of a channel
all settings works on API explorer but when I try it in the client it not working
other things of youtube data api3 like channel and playlistitems working, my problem is just with playlist.list
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for full read/write access to the
// authenticated user's account.
new[] { YouTubeService.Scope.Youtube },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var channelVids = youtubeService.Playlists.List("snippet");
channelVids.Id = "UCIabPXjvT5BVTxRDPCBBOOQ";
//channelVids.Fields = "items(id,snippet(description,publishedAt,thumbnails/default/url,title)),nextPageToken";
channelVids.MaxResults = 25;
var results = await channelVids.ExecuteAsync();
Console.WriteLine(results.Items.Count + " lists");
I found my solution
it was just a typo
channelVids.Id = "UCIabPXjvT5BVTxRDPCBBOOQ";
to
channelVids.ChannelId = "UCIabPXjvT5BVTxRDPCBBOOQ";

Google Drive API integration is not working with live URL

i am trying to upload documents using google Drive API integration, working fine in case of localhost but not working on live domain.
using (var stream = new FileStream(#"" + folderPathForCredentials, FileMode.Open, FileAccess.ReadWrite))
{
// 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.
String FolderPath = #"" + folderPathForToken;
String FilePath = Path.Combine(FolderPath, "token.json");
stream.Dispose();
stream.Close();
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = clientID,
ClientSecret = clientSecret
},
Scopes,
"user",
CancellationToken.None,
new FileDataStore(FilePath, true)).Result;
}
//create Drive API service.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName,
});
return service;
And this is the code to Upload on Google Drive.
FilesResource.CreateMediaUpload request;
if (System.IO.File.Exists(path))
{
using (var stream = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
request = _service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
request.Fields = "id";
request.Upload();
stream.Dispose();
stream.Close();
System.IO.File.Delete(path);
//return request.ResponseBody;
return Json(new JsonData { IsSuccess = true, Message = "Uploaded Successfully", Data = null });
}
}
Let me help in configuring the drive with live domain.

Can't access data from Google Sheet, using Google Sheets API, and C# WPF - Without logging in

Below is the code I use to obtain the data from my spreadsheet. This works if I am logged into google+, but that isn't the intention, as I want users to access the data through this application.
When I build and provide the files to a user on another PC, it doesn't even start the application, on my own, it can at least start
String myUrl =
"http://nofile.io/g/[REDACTED]/client_secret.json";
WebClient client = new WebClient(); {
client.DownloadFile(myUrl, "\\client_secret.json");
}
UserCredential credential;
using (var stream =
new FileStream("\\client_secret.json", FileMode.Open, FileAccess.Read)) {
string credPath = Environment.GetFolderPath(
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);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer {
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});
// Define request parameters.
String spreadsheetId = "1uLxm0jvmL1_FJNYUJp6YqIezzqrZdjPf2xQGOWYd6ao";
String range = "TestSheet!A1:F";
SpreadsheetsResource.ValuesResource.GetRequest request =
service.Spreadsheets.Values.Get(spreadsheetId, range);
File.Delete("\\client_secret.json");

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

Request had insufficient authentication scopes. [403] 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!

Categories

Resources