Google云端硬盘Api获取当前用户

时间:2017-04-09 20:40:21

标签: c# asp.net-mvc google-api google-drive-api

我正在关注位于以下位置的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;  

通过实施的表格,将始终使用相同的权限(第一个),因为它必须链接到“用户”字段。

我的问题:

  1. 如何搜索登录Google的当前帐户以将其置于user字段中?
  2. 如果用户未登录,他无法访问任何内容?
  3. 我应该更改user字段或许可证路径,还是同时更改用户x无法访问用户数据y
  4. 如果在权限屏幕上如下图所示,如果用户关闭浏览器或拒绝访问,那么页面的最佳做法是什么?
  5. enter image description here

2 个答案:

答案 0 :(得分:0)

  1. 您无需在此处查找当前用户的姓名即可输入。 "用户" field - 只是凭证的快捷方式名称(文件名的一部分),它将保存在文件数据存储中,与您在此处输入的内容无关,但每个文件数据存储必须是唯一的。
  2. 如果用户的凭据未存储在文件数据存储中,或者用户未登录或已登录但未授予应用程序许可权 - 应用程序无法访问任何内容
  3. 对于您要访问的Google云端硬盘用户,您必须输入唯一的名称。关于许可路径是什么不太清楚。
  4. 您可以尝试以下代码,或者最好使用google samples here
  5. 进行检查
    // 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();