我正在关注位于以下位置的Google Drive Api文档: https://developers.google.com/drive/v3/web/quickstart/dotnet
我已将文件夹更改为其他特定文件夹。
string credPath = Server.MapPath(@"~\googleDrive");
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
通过实施的表格,将始终使用相同的权限(第一个),因为它必须链接到“用户”字段。
答案 0 :(得分:0)
// Time-out in milliseconds, after which auth process will be terminated, whether permission granted or not
var timeoutMs = 60*1000;
var credCts = new CancellationTokenSource(timeoutMs);
var credPath = ".credentials/app-user-credentials"; //<-- In API refs ctor definead as FileDataStore(string folder, [bool fullPath = False]), credPath must be a folder name, not a file name as in your code
var authTask = GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, Scopes, "someuniqueusername",
credCts.Token, new FileDataStore(credPath, true));
UserCredential credential = null;
try
{
if (authTask.Wait(timeoutMs, credCts.Token))
{
credential = authTask.Result;
}
else
{
throw new OperationCanceledException("Auth time-out");
}
}
catch (Exception ex)
{
Logger.Error(ex.Message);
throw;
}
finally
{
credCts.Dispose();
if (authTask.IsCanceled || authTask.IsCompleted || authTask.IsFaulted)
authTask.Dispose();
}
// do some stuff...
更新:
成功收到UserCredentials
后(第一次或存储在FileDataStore
中),要获得授权用户的电子邮件,您可以使用此功能:
private static string GetUserEmail2(UserCredential credential)
{
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Name-Of-Your-Google-App",
});
var about = service.About.Get().Execute();
return about.User.EmailAddress;
}
答案 1 :(得分:0)
感谢https://stackoverflow.com/a/16168206/13513993的解决方案,您必须使用Outh2 API:-
using Google.Apis.Oauth2.v2;
using Google.Apis.Oauth2.v2.Data;
添加范围(电子邮件):-
public static string[] Scopes = { Google.Apis.Drive.v3.DriveService.Scope.DriveReadonly, "email" };
您可以从:-
获取证书credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(FilePath, true)).Result;
}
然后使用以下功能:-
var oauthSerivce = new Oauth2Service(new BaseClientService.Initializer { HttpClientInitializer = credential });
UserInfo = oauthSerivce.Userinfo.Get().Execute();