如何安全存储Google Drive API提供的每个用户的OAuth响应文件

时间:2019-05-18 18:24:05

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

我正在开发一个asp.net应用程序,在该应用程序中,我要求人们给予授权(使用OAuth)来访问其Google驱动器(到特定文件夹),以便能够在应用程序中列出文件。

以下代码使用户能够提供授权,并在服务器中创建相应的Google.Apis.Auth.OAuth2.Responses文件以用于将来的请求。但是,此请求将针对每个用户发生,这将创建更多OAuth响应文件。我不确定如何设计应用程序并安全地存储这些文件。可能我可以为每个用户创建一个新文件夹(使用Guid-based UserIds)并将文件保存在该文件夹中。这有意义吗?还是您建议另一种方法?

using (var stream =
    new FileStream("Services/credentials.json", FileMode.Open, FileAccess.Read))
{
    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);
}

BaseClientService.Initializer bcs = new BaseClientService.Initializer();
bcs.HttpClientInitializer = credential;

DriveService service = new DriveService(bcs);

1 个答案:

答案 0 :(得分:1)

更正

  

我正在开发一个asp.net应用程序,在该应用程序中,我要求人们给予授权(使用OAuth)以访问其Google驱动器(到特定文件夹),以便能够在应用程序中列出文件。

当您请求访问权限时,它将成为用户完整的驱动器帐户,而不仅仅是一个文件夹。

存储凭据文件。

您的问题有点难以理解,但我认为您正在询问应将凭证文件存储在何处。 FileDataStore的工作方式是为每个"user"创建一个新文件,因此根据您为“用户”设置的内容,将创建一个文件,如您所见,我倾向于在结束并将其存储在会话变量中,这样我就知道用户何时返回此会话变量,该文件是我需要为他们抓取的。实际上,客户端库会为您完成所有操作,因为一旦看到ID,它将自动使用该ID。

enter image description here

Web与已安装的应用程序。

如果您使用Asp .net并打算使用Web应用程序,那么我确实有一条主要评论,那么您使用的是错误的代码。以下示例显示了如何使用Web appliations asp.net mvc进行身份验证,请注意以下代码中的会话。

 public class AppFlowMetadata : FlowMetadata
    {
        private static readonly IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = "PUT_CLIENT_ID_HERE",
                        ClientSecret = "PUT_CLIENT_SECRET_HERE"
                    },
                    Scopes = new[] { DriveService.Scope.Drive },
                    DataStore = new FileDataStore("Drive.Api.Auth.Store")
                });

        public override string GetUserId(Controller controller)
        {
            // In this sample we use the session to store the user identifiers.
            // That's not the best practice, because you should have a logic to identify
            // a user. You might want to use "OpenID Connect".
            // You can read more about the protocol in the following link:
            // https://developers.google.com/accounts/docs/OAuth2Login.
            var user = controller.Session["user"];
            if (user == null)
            {
                user = Guid.NewGuid();
                controller.Session["user"] = user;
            }
            return user.ToString();

        }

        public override IAuthorizationCodeFlow Flow
        {
            get { return flow; }
        }
    }