我已授权DriveService
个对象。有没有办法获得授权用户的电子邮件?我可以获取显示名称,但不能获取电子邮件地址。
OAuth2Authenticator auth = new OAuth2Authenticator<NativeApplicationClient>(provider, client => GetAuthorization(client));
DriveService service = new DriveService(
new BaseClientService.Initializer()
{
Authenticator = auth
}
);
Console.WriteLine(service_.About.Get().Fetch().User.DisplayName);
GetAuthorization
功能打开浏览器并允许用户进行授权。
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
IAuthorizationState state = new AuthorizationState(new[]
{
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.metadata.readonly",
"https://www.googleapis.com/auth/drive.readonly"
});
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
using (LoginWindow login = new LoginWindow(arg.RequestUserAuthorization(state).ToString()))
{
if (login.ShowDialog() == DialogResult.OK)
{
return arg.ProcessUserAuthorization(login.AuthorizationToken, state);
}
}
throw new UnauthorizedAccessException();
}
提前致谢。
答案 0 :(得分:1)
将此网址添加到范围:
它加载名称,公开个人资料网址,电子邮件,性别,照片等。
在获得授权后,从Json回复中获取信息:
IAuthorizationState state = new AuthorizationState(new[]
{
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.metadata.readonly",
"https://www.googleapis.com/auth/drive.readonly"
"https://www.googleapis.com/auth/userinfo.email"
});
修改强>
将范围添加到AuthorizationState构造函数
List<string> scopes = new List<string>();
scopes.Add("https://www.googleapis.com/auth/userinfo.email");
答案 1 :(得分:0)
使用此代码:
private string FetchUsersEmail()
{
var emailRequest = @"https://www.googleapis.com/userinfo/email?alt=json&access_token=" + GoogleAccessToken;
string jsonString;
var request = WebRequest.Create(emailRequest);
using (var response = (HttpWebResponse)request.GetResponse())
using (var dataStream = response.GetResponseStream())
using (var reader = new StreamReader(dataStream))
{
jsonString = reader.ReadToEnd();
}
var json = JToken.Parse(jsonString);
var currentGoogleEmail = json["data"]["email"].Value<string>();
return currentGoogleEmail;
}
我使用Newtonsoft来解析json,但你可以使用任何其他库。
答案 2 :(得分:0)
DriveService driveService = ...
var req = driveService.About.Get();
req.Fields = "user(displayName,photoLink, me, emailAddress), storageQuota(limit,usage), maxImportSizes, maxUploadSize";
About ab = await req.ExecuteAsync();