c# - 如何在 .Net 的 GoogleWebAuthorizationBroker.AuthorizeAsync 方法中发送存储为 json 字符串(在数据库中)的 Google 驱动 token ?

标签 c# google-api google-drive-api google-oauth google-api-dotnet-client

我正在将 Google token 转换为 json 字符串格式并将该字符串存储在数据库中。

现在在谷歌驱动器中上传文件时,我想在 GoogleWebAuthorizationBroker.AuthorizeAsync 方法中发送该 json 以获取用于获取 DriveService 的凭据。

因此我可以创建一个后台任务来检查 token 并自动上传文件而无需用户交互。 我也可以使用该凭证创建新的 json 文件并保存在数据库中,这样如果访问 token 更新,它可以自动存储。

UserCredential credential;    

credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        new ClientSecrets
                        {
                            ClientId = "",
                            ClientSecret = ""
                        },
                        new[] { DriveService.Scope.Drive },
                        Page.User.Identity.Name,
                        CancellationToken.None).Result;

string json = JsonConvert.SerializeObject(credential.Token);

var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Test",
            });

我做的对吗?或者有没有其他方法可以将凭据保存在数据库中而不是保存在文件中?

最佳答案

假设我对你的理解是正确的,你正在将刷新 token 保存到数据库中,并希望稍后使用它来访问 API。

您应该做的是仅存储刷新 token ,然后创建您自己的 idatastore 实现来加载它。目前您正在使用 filedatastore,它将在存储在 %appdata% 中的文件中查找它

我这里有一堆例子database datastores但这里是 Entity Framework 的,因为你还没有说你正在使用哪个数据库。

using Google.Apis.Json;
using Google.Apis.Util.Store;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace GoogleAuthDataStores
{
    public class GoogleUserCredential
    {
        [Key]
        public int ID { get; set; }

        [Required, Index(IsUnique = true), StringLength(500)]
        public string Key { get; set; }

        [Required]
        public string Credentials { get; set; }
    }

    internal class EntityFrameworkDataStore : DbContext, IDataStore
    {
        public DbSet<GoogleUserCredential> GoogleUserCredentials { get; set; }

        /// <summary>The string used to open the connection.</summary>
        public virtual string ConnectionString { get; set; }

        /// <summary>
        /// Creates a new table in the data base if the Users table does not exist within the database used in the connectionstring.
        /// </summary>
        /// <param name="connectionString">The string used to open the connection.</param>
        public EntityFrameworkDataStore(string connectionString) : base(connectionString)
        {
            ConnectionString = connectionString;
        }

        /// <summary>
        /// Stores the given value for the given key. It creates a new row in the database with the user id of
        /// (primary key <see cref="GenerateStoredKey"/>) in <see cref="GoogleUserCredentials"/>.
        /// </summary>
        /// <typeparam name="T">The type to store in the data store.</typeparam>
        /// <param name="key">The key.</param>
        /// <param name="value">The value to store in the data store.</param>
        Task IDataStore.StoreAsync<T>(string key, T value)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }

            var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
            save(GenerateStoredKey(key), serialized);
            return Task.Delay(0);
        }

        /// <summary>
        /// Deletes the given key. It deletes the <see cref="GenerateStoredKey"/> row in
        /// <see cref="GoogleUserCredentials"/>.
        /// </summary>
        /// <param name="key">The key to delete from the data store.</param>
        Task IDataStore.DeleteAsync<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }

            try
            {
                var hold = GoogleUserCredentials.Where(a => a.Key == key).FirstOrDefault();
                GoogleUserCredentials.Remove(hold);
                SaveChangesAsync();
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception("Failed to delete credentials", ex);
            }

            return Task.Delay(0);
        }

        /// <summary>
        /// Returns the stored value for the given key or <c>null</c> if the matching row (<see cref="GenerateStoredKey"/>
        /// in <see cref="GoogleUserCredentials"/> doesn't exist.
        /// </summary>
        /// <typeparam name="T">The type to retrieve.</typeparam>
        /// <param name="key">The key to retrieve from the data store.</param>
        /// <returns>The stored object.</returns>
        Task<T> IDataStore.GetAsync<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }

            TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
            var user = GetUserByKey(GenerateStoredKey(key));
            if (user != null)
            {
                try
                {
                    tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize<T>(user.Credentials));
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }
            else
            {
                tcs.SetResult(default(T));
            }
            return tcs.Task;
        }

        /// <summary>
        /// Clears all values in the data store. This method deletes all files in <see cref="GoogleUserCredentials"/>.
        /// </summary>
        Task IDataStore.ClearAsync()
        {
            try
            {
                foreach (var item in GoogleUserCredentials)
                {
                    GoogleUserCredentials.Remove(item);
                }
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception("Failed to clear credentials", ex);
            }

            return Task.Delay(0);
        }

        /// <summary>
        /// Checks if the user exists <see cref="GenerateStoredKey"/>.
        /// </summary>
        private GoogleUserCredential GetUserByKey(string key)
        {
            try
            {
                var user = GoogleUserCredentials.Where(a => a.Key == key).FirstOrDefault();

                if (user != null)
                    return user;

                return null;
            }
            catch (System.Data.SqlClient.SqlException)
            {
                return null;
            }
        }

        /// <summary>
        /// Save the credentials.  If the user <see cref="GenerateStoredKey"/> does not exists we insert it other wise we will do an update.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="serialized"></param>
        private void save(string key, string serialized)
        {
            try
            {
                var user = GoogleUserCredentials.Where(a => a.Key == key).FirstOrDefault();
                if (user == null)
                {
                    var hold = new GoogleUserCredential { Key = key, Credentials = serialized };
                    GoogleUserCredentials.Add(hold);
                }
                else
                {
                    var aUser = this.GoogleUserCredentials.Where(a => a.Key == key).FirstOrDefault();
                    aUser.Credentials = serialized;
                }
                SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>Creates a unique stored key based on the key and the current project name.</summary>
        /// <param name="key">The object key.</param>
        public static string GenerateStoredKey(string key)
        {
            return string.Format("{0}-{1}", Assembly.GetCallingAssembly().GetName().Name, key);
        }
    }
}

关于c# - 如何在 .Net 的 GoogleWebAuthorizationBroker.AuthorizeAsync 方法中发送存储为 json 字符串(在数据库中)的 Google 驱动 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52045751/

相关文章:

c# - 在 C# 中继承事件处理程序

unicode - Google 计算器中的特殊字符

javascript - 类型错误 : Cannot find function hasNext in object

c# - 即使使用更新面板,页面也会跳转到页面顶部

c# - 是否存在任何NON-GPL/AGPL病毒扫描库?

c# - 如何查找 DetailsView 中的哪个页面包含选定的 GridView 行

google-api - 是否有可供 3rd 方产品使用的 Google Forms API?

google-api - Google 的 UrlShortener,在哪里可以找到该列表

python-3.x - Google Drive API Python 服务帐户示例

javascript + html5 音频播放器cors不播放动态源码