0

I'm using Google Sheet API V4 in C#. My source will create new Excel file, write data to that file.

When execute, Google API will open a new OAuth tab on the browser, User will choose/login to an email on this tab, and grant Read/Write/All permission for my App.

My question is: How can I get Logged/permitted email address in C# source? I want to know, what email did the user log in to create myfile.xlsx.

Thanks in advance. Code snippet:

string[] Scopes = { SheetsService.Scope.DriveFile };
string ApplicationName = "Google Sheets API";

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.
    string credPath = "token.json";
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        Scopes,
        "UserName",
        CancellationToken.None,
        new FileDataStore(credPath, true)).Result;
    Console.WriteLine("Credential file saved to: " + credPath);
}

var fileName = "myfile.xlsx";

var myNewSheet = new Spreadsheet();
myNewSheet.Properties = new SpreadsheetProperties();
myNewSheet.Properties.Title = fileName;

var sheet = new Sheet();
sheet.Properties = new SheetProperties();
sheet.Properties.Title = $"data";

myNewSheet.Sheets = new List<Sheet>() { sheet };

var newSheet = service.Spreadsheets.Create(myNewSheet).Execute();
var spreadSheetId = newSheet.SpreadsheetId;
...........
// Write data to file source
Dieu Luong
  • 133
  • 3
  • 12

1 Answers1

-1

Google Indentiy platform describes the procedure of how to authenticate a user to obtain user information and more specifically user profile information

  • The documentation does not specify how exactly to do it in C#, but basically

    • Make a GET request to https://www.googleapis.com/oauth2/v3/userinfo
    • Provide the scopes https://www.googleapis.com/auth/userinfo.profile and https://www.googleapis.com/auth/userinfo.email
    • There is a good sample on Stackoverflow how to do it in PHP - I hope it helps you with the implementation in C#
  • There is also a workaround authenticating users with Gmail

ziganotschka
  • 25,866
  • 2
  • 16
  • 33