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

可紊 提交于 2020-07-22 10:55:22

问题


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? 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. I'm getting error "Google.Apis.Requests.RequestError Legacy People API has not been used in project 618254727025 before or it is disabled"


回答1:


solution is to get access token and try https://www.googleapis.com/oauth2/v2/userinfo?access_token=




回答2:


  • In your scopes variable. Try and just use the value "email" not the full https address. Scope keywords in the web link are separated by spaces. Here is a way that I do this to obtain the scopes: 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]

  • fyi: I was ammending the demonstration code available: 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);
    



回答3:


You can use the users.getprofile it will return the email address of the user who is currently authenticated.

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"

 var request = plusService.People.Get("people/me")
 request.PersonFields("emailAddresses");
 var response = request.Execute();


来源:https://stackoverflow.com/questions/62612997/how-to-get-email-after-using-google-oauth2-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!