我使用代码获取凭据
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;
}
如何从此凭证获取电子邮件?我试过代码
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 旧版 People API 之前未在项目 618254727025 中使用或已禁用”
在您的scopes变量中。尝试只使用值“电子邮件”而不是 完整的 https 地址。 Web 链接中的范围关键字以空格分隔。这是我获取范围的方法:个人资料电子邮件 openid。
要测试此方法,您可以在获取访问代码后手动将以下网页链接粘贴到浏览器中: https://www.googleapis.com/oauth2/v2/userinfo?access_token=[在此处粘贴访问代码]&[在此处粘贴以下变量的值authorizationRequest]
fyi:我正在修改可用的演示代码: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);
您可以使用 users.getprofile 它将返回当前经过身份验证的用户的电子邮件地址。
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "My Application",
});
var user = service.Users.GetProfile("me").Execute;
{
"emailAddress": "[email protected]",
"messagesTotal": 8394,
"threadsTotal": 1494,
"historyId": "605503"
}
people.get的正确用法是“people/me”
var request = plusService.People.Get("people/me")
request.PersonFields("emailAddresses");
var response = request.Execute();
我已经被这个问题困扰好几天了。最后,由于这个链接(检查用户是否已经登录),我了解到参数输入“user”是关键问题。这个“用户”应该是windows登录用户(可以用
Enviroment.Username
),而不是程序员或者APP用户。 GoogleWebAuthorizationBroker.AuthorizeAsync
使用此用户名将其凭证保存在以下位置:
C:\Users[用户名]\AppData\Roaming\Google.Apis.Auth\Google.Apis.Auth.OAuth2.Responses.TokenResponse-[用户名]
(类似这样)。 因此,如果您将“用户”提供给
AuthorizeAsync
,则凭据保存可能会出现问题,并且您的应用程序将挂起或严重滞后。而且,以后当你想使用cred文件来获取userinfo和email时,就会出现问题(严重滞后)。就我而言,用户信息将全部丢失,只留下电子邮件地址。此外,您还必须包含所需的两个范围:“https://www.googleapis.com/auth/userinfo.email”、“https://www.googleapis.com/auth/userinfo.profile”。希望这些有帮助。
oauth2Client
。id_token
,它基本上是一个jwt
token,解析它你会得到email
。有什么方法可以将 GAIA ID(Google 标识符)转换为电子邮件吗?