簡體   English   中英

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

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

我使用代碼獲取憑據

 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;
    }

如何從此憑證中獲取 email? 我試過代碼

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;
    }

但看起來 People.Get("me") 不再可行了。 我收到錯誤消息“Google.Apis.Requests.RequestError Legacy People API 之前未在項目 618254727025 中使用或已被禁用”

解決方案是獲取訪問令牌並嘗試https://www.googleapis.com/oauth2/v2/userinfo?access_token=

您可以使用users.getprofile它將返回當前經過身份驗證的用戶的 email 地址。

要求

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

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

回復

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

人我

people.get的正確用法是“people/me”

 var request = plusService.People.Get("people/me")
 request.PersonFields("emailAddresses");
 var response = request.Execute();
  • 在您的范圍變量中。 嘗試使用值“email”而不是完整的 https 地址。 web 鏈接中的 Scope 關鍵字以空格分隔。 這是我獲取范圍的一種方法:profile email openid。

  • 要測試這種方法,您可以在獲取訪問代碼后手動將以下鏈接粘貼到瀏覽器中: https://www.googleapis.com/oauth2/v2/userinfo?access_token=[PASTE ACCESS CODE HERE]&[PASTE VALUE FROM下面的變量授權請求在這里]

  • 僅供參考:我正在修改可用的演示代碼: 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);

我已經在這個問題上停留了幾天。 最后,感謝這個鏈接( 檢查用戶是否已經登錄),我了解到參數輸入“用戶”是關鍵問題。 這個“用戶”應該是 windows 登錄用戶(可以使用Enviroment.Username ),而不是程序員或APP用戶。 GoogleWebAuthorizationBroker.AuthorizeAsync使用此用戶名將其憑據保存在以下位置:

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

(像這樣)。 因此,如果您將“用戶”提供給AuthorizeAsync ,則憑證保存可能會出現問題,並且您的應用程序將嚴重掛起或滯后。 而且,以后想用cred文件獲取userinfo和email的時候,會出現問題(嚴重滯后)。 在我的情況下,用戶信息將全部丟失,只留下一個 email 地址。 此外,您必須包含所需的兩個范圍:“https://www.googleapis.com/auth/userinfo.email”、“https://www.googleapis.com/auth/userinfo.profile”。 希望這些有所幫助。

  1. 在范圍中添加“https://www.googleapis.com/auth/userinfo.email”。
  2. 在回調中,您將編碼。 使用 oauth2Client 從此代碼中獲取令牌oauth2Client
  3. 這個 json 包含id_token ,它基本上是一個 jwt 令牌,解析它你會得到email

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM