简体   繁体   English

在C#中使用google OAuth2后如何获得email?

[英]how to get email after using google OAuth2 in C#?

I get credentials using code我使用代码获取凭据

 static string[] Scopes = { "https://www.googleapis.com/auth/userinfo.email" };

    private static UserCredential GenerateCredential()
    {
        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,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

        return credential;
    }

How to get email from this credential?如何从此凭证中获取 email? I've tried code我试过代码

private string GetEmailFromCredentials(UserCredential credential)
    {
        var plusService = new PlusService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "My Application",
        });

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

        return useremail;
    }

but it looks like that People.Get("me") is not possibe anymore.但看起来 People.Get("me") 不再可行了。 I'm getting error "Google.Apis.Requests.RequestError Legacy People API has not been used in project 618254727025 before or it is disabled"我收到错误消息“Google.Apis.Requests.RequestError Legacy People API 之前未在项目 618254727025 中使用或已被禁用”

solution is to get access token and try https://www.googleapis.com/oauth2/v2/userinfo?access_token=解决方案是获取访问令牌并尝试https://www.googleapis.com/oauth2/v2/userinfo?access_token=

You can use the users.getprofile it will return the email address of the user who is currently authenticated.您可以使用users.getprofile它将返回当前经过身份验证的用户的 email 地址。

request要求

 var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "My Application",
        });

  var user = service.Users.GetProfile("me").Execute;

response回复

{
  "emailAddress": "xxxx1@gmail.com",
  "messagesTotal": 8394,
  "threadsTotal": 1494,
  "historyId": "605503"
}

People me人我

The correct usage of people.get is "people/me" people.get的正确用法是“people/me”

 var request = plusService.People.Get("people/me")
 request.PersonFields("emailAddresses");
 var response = request.Execute();
  • In your scopes variable.在您的范围变量中。 Try and just use the value "email" not the full https address.尝试使用值“email”而不是完整的 https 地址。 Scope keywords in the web link are separated by spaces. web 链接中的 Scope 关键字以空格分隔。 Here is a way that I do this to obtain the scopes: profile email openid.这是我获取范围的一种方法:profile email openid。

  • To test this approach, you can manually paste the below weblink into a browser after obtaining the access code: https://www.googleapis.com/oauth2/v2/userinfo?access_token=[PASTE ACCESS CODE HERE]&[PASTE VALUE FROM THE BELOW VARIABLE authorizationRequest HERE]要测试这种方法,您可以在获取访问代码后手动将以下链接粘贴到浏览器中: https://www.googleapis.com/oauth2/v2/userinfo?access_token=[PASTE ACCESS CODE HERE]&[PASTE VALUE FROM下面的变量授权请求在这里]

  • fyi: I was ammending the demonstration code available: https://github.com/googlesamples/oauth-apps-for-windows .仅供参考:我正在修改可用的演示代码: https://github.com/googlesamples/oauth-apps-for-windows

     // Creates the OAuth 2.0 authorization request. string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile%20email&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}", authorizationEndpoint, System.Uri.EscapeDataString(redirectURI), clientID, state, code_challenge, code_challenge_method);

I have been stuck on this issue for several days.我已经在这个问题上停留了几天。 And finally, thanks to this link ( Check if user is already logged in ), I learned that the parameter input, "user", to be the key issue.最后,感谢这个链接( 检查用户是否已经登录),我了解到参数输入“用户”是关键问题。 This "user" should be the windows login user (you can use Enviroment.Username ), not the programmer or APP user.这个“用户”应该是 windows 登录用户(可以使用Enviroment.Username ),而不是程序员或APP用户。 The GoogleWebAuthorizationBroker.AuthorizeAsync uses this username to save its credential in the location: GoogleWebAuthorizationBroker.AuthorizeAsync使用此用户名将其凭据保存在以下位置:

C:\Users[username]\AppData\Roaming\Google.Apis.Auth\Google.Apis.Auth.OAuth2.Responses.TokenResponse-[username] C:\Users[用户名]\AppData\Roaming\Google.Apis.Auth\Google.Apis.Auth.OAuth2.Responses.TokenResponse-[用户名]

(something like this). (像这样)。 So if you feed "user" to AuthorizeAsync , the credential saving could be a problem, and your app will hang or lag seriously.因此,如果您将“用户”提供给AuthorizeAsync ,则凭证保存可能会出现问题,并且您的应用程序将严重挂起或滞后。 And, later when you want to use the cred file to get userinfo and email, it will be problematic (lag seriously).而且,以后想用cred文件获取userinfo和email的时候,会出现问题(严重滞后)。 In my case, user info will be all missing, leaving only an email address.在我的情况下,用户信息将全部丢失,只留下一个 email 地址。 Also, you have to include the required two scopes: "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile".此外,您必须包含所需的两个范围:“https://www.googleapis.com/auth/userinfo.email”、“https://www.googleapis.com/auth/userinfo.profile”。 Hope these helps.希望这些有所帮助。

  1. Add 'https://www.googleapis.com/auth/userinfo.email' in scopes.在范围中添加“https://www.googleapis.com/auth/userinfo.email”。
  2. In callback you will code.在回调中,您将编码。 Get tokens json from this code using oauth2Client .使用 oauth2Client 从此代码中获取令牌oauth2Client
  3. This json contains id_token which is basically a jwt token, parse it u will get email .这个 json 包含id_token ,它基本上是一个 jwt 令牌,解析它你会得到email

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

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