简体   繁体   中英

C# Google OAuth2 get email of the user currently login

I just recently try Google Apis and totally new to this. i had spent last 2 hour searching how to get the email that allow the access of the API and how to refresh token automatically.

My code are pretty much same as the tutorial

class GoogleAPI
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
        static string[] Scopes = { SheetsService.Scope.Spreadsheets };
        static string ApplicationName = "Google Sheets API .NET Quickstart";

        public GoogleAPI()
        {
            UserCredential credential;

            using (var stream =
                new FileStream("Secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/Secret_Credentials.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 = "1Jd9NgmnfvJzPtjXw_jNzSUAlOO532mF6ebYyIIle_H8";
            String range = "Sheet1!A:L";
            SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);

            ValueRange response = request.Execute();

            var a = response;
            System.Windows.Forms.MessageBox.Show("success");

        }
    }

After searching, i assume that my token will automatically refreshed when expired, so i'm left with 1 problem.

The problem: How i can get the email of the user that are saved in the credentials.

I'm really new to this, please help me by explaining it really detailed.


Thanks to @DaImTo

I finally understand how to add it. his tutorial -> http://www.daimto.com/find-users-email-with-google-api/

The code to make it works.

First We need to add "email" as scopes and remember to delete your old credentials.

static string[] Scopes = { SheetsService.Scope.Spreadsheets, "email" };

Secondly, create the service for the google plus.

// Create Google Plus API service.
var plusService = new PlusService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = ApplicationName,
});

And finally, get the email

var me = plusService.People.Get("me").Execute();
var useremail = me.Emails.FirstOrDefault().Value;

why do you want an email exactly?

access token allows access to the API. Refresh token will update the access token automcatcly when it expires (1 hour) that's what FileDataStore does.

File data store already saved your credentials in %appData% if I am reading the credPath path correctly.

The only way I know of to get the current authenticated users email is to go though the Google+ api People.get send me. You will need to add another scope to your request.

If using the userId value "me", this method requires authentication using a token that has been granted the OAuth scope https://www.googleapis.com/auth/plus.login or https://www.googleapis.com/auth/plus.me . Read more about OAuth.

code:

Nuget package:

PM> Install-Package Google.Apis.Plus.v1

Code

var me = plusService.People.Get("me").Execute();
var useremail = me.Emails.FirstOrDefault().Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM