简体   繁体   English

C#Google OAuth2获取当前登录用户的电子邮件

[英]C# Google OAuth2 get email of the user currently login

I just recently try Google Apis and totally new to this. 我最近才尝试使用Google Apis,这是一个全新的尝试。 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. 我花了最后2个小时来搜索如何获取允许访问API的电子邮件以及如何自动刷新令牌。

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. 搜索后,我假设我的令牌过期后会自动刷新,所以我有1个问题。

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 感谢@DaImTo

I finally understand how to add it. 我终于知道如何添加它。 his tutorial -> http://www.daimto.com/find-users-email-with-google-api/ 他的教程-> 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. 其次,为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. 访问令牌允许访问API。 Refresh token will update the access token automcatcly when it expires (1 hour) that's what FileDataStore does. 刷新令牌将在FileDataStore进行的过期(1小时)到期时自动更新访问令牌。

File data store already saved your credentials in %appData% if I am reading the credPath path correctly. 如果我正确读取credPath路径,则文件数据存储区已将您的凭据保存在%appData%中。

The only way I know of to get the current authenticated users email is to go though the Google+ api People.get send me. 我知道要获取当前经过身份验证的用户的电子邮件的唯一方法是通过Google+ API People.get发送给我。 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 . 如果使用userId值“ me”,则此方法需要使用已授予OAuth作用域https://www.googleapis.com/auth/plus.loginhttps://www.googleapis.com/auth的令牌的身份验证/plus.me Read more about OAuth. 进一步了解OAuth。

code: 码:

Nuget package: Nuget包:

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

Code

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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