我已成功使用GoogleWebAuthorizationBroker将用户凭据保存到文件中.但我希望我的应用程序更安全一点.因此,我试图将凭据保存到我的sqlite数据库中.我已经完成了实体框架类,但现在我不确定如何使用它将数据保存到数据库.这是我当前的代码

return GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.FromStream(stream).Secrets,
                    _scopes,
                    "user",
                    CancellationToken.None,
                    GoogleCredentialsDataStore.GenerateStoredKey("What string value goes here")

因此,我有点不知道什么字符串值进入GenerateStoredKey参数,以便它将处理并保存到我的数据库中.

这是项目的数据接口部分.

public class GoogleCredentialsDataStore : SqLiteDbContext, IDataStore
    {
        /// <summary>
        /// Database context to access database
        /// </summary>
        private readonly SqLiteDbContext _context;
        public GoogleCredentialsDataStore(SqLiteDbContext context)
        {
            _context = context;
        }

        /// <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 ArgumentNullException("key Must have a value");
            }

            var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);

            _context.GoogleCredentials.Add(new()
            {
                Key = GenerateStoredKey(key),
                Credentials = serialized
            });
            _context.SaveChanges();
            return Task.Delay(0);
        }
        /// <summary>
        /// Deletes the given key. It deletes the <see cref="GenerateStoredKey"/> row in
        /// <see cref="GoogleCredentials"/>.
        /// </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 = _context.GoogleCredentials.Where(a => a.Key == key).FirstOrDefault();
                _context.GoogleCredentials.Remove(hold);
                _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw new Exception("Failed to delete credentials");
            }

            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="GoogleCredentials"/> 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="GoogleCredentials"/>.
        /// </summary>
        Task IDataStore.ClearAsync()
        {
            try
            {
                foreach (var item in _context.GoogleCredentials)
                {
                    _context.GoogleCredentials.Remove(item);
                }
            }
            catch (Exception)
            {
                throw new Exception("Failed to clear credentials");
            }

            return Task.Delay(0);
        }

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

                if (user != null)
                    return user;

                return null;
            }
            catch (Exception)
            {
                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 = _context.GoogleCredentials.Where(a => a.Key == key).FirstOrDefault();
                if (user == null)
                {
                    var hold = new GoogleCredentials { Key = key, Credentials = serialized };
                    _context.GoogleCredentials.Add(hold);
                }
                else
                {
                    var aUser = _context.GoogleCredentials.Where(a => a.Key == key).FirstOrDefault();
                    aUser.Credentials = serialized;
                }
                _context.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <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);
        }
    }

然后是我的谷歌认证模型

public class GoogleCredentials
    {
        [Key]
        public int Id { get; set; }
        [Required, StringLength(500)]
        public string Key { get; set; }
        [Required]
        public string Credentials { get; set; }
    }

这对我来说还是 fresh 事,但这就是我所拥有的,我认为我所理解的方向是正确的,但也许一些更有知识的人可以看看,让我走上正确的道路.

推荐答案

构造函数接受连接字符串.

  public static UserCredential InstalledCredential(string credFilePath, string[] scopes, string userName, string connectionString)
        {
            return GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(credFilePath).Secrets,
                scopes,
                userName,
                CancellationToken.None,
                new EntityFrameworkDataStore(connectionString)).Result;
        }

EntityFrameworkDataStore

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

    /// <summary>The string used to open the connection.</summary>
    public 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");
        }

        var 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
        {
            return GoogleUserCredentials.FirstOrDefault(a => a.Key == key);
        }
        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)
    {
        var user = GoogleUserCredentials.FirstOrDefault(a => a.Key == key);
        if (user == null)
        {
            var hold = new GoogleUserCredential { Key = key, Credentials = serialized };
            GoogleUserCredentials.Add(hold);
        }
        else
        {
            var aUser = GoogleUserCredentials.FirstOrDefault(a => a.Key == key);
            aUser.Credentials = serialized;
        }

        SaveChanges();
    }

    /// <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 $"{Assembly.GetCallingAssembly().GetName().Name}-{key}";
    }
}

Csharp相关问答推荐

WPF文本框点击鼠标 Select 内容

System.Text.Json:反序列化返回为空数组的字典时出错

如何从C#中有类.x和类.y的类列表中映射List(字符串x,字符串y)?

下拉图片点击MudBlazor

此反射有什么问题.是否发送值转换委托?

创建临时Collection 最有效的方法是什么?堆栈分配和集合表达式之间的区别?

StackExchange.Redis.RedisServerException:调用ITransaction.ExecuteAsync()时出现错误未知命令取消监视

ASP.NET核心MVC SqlException:违反主键约束';PK_USER';.无法在对象';数据库中插入重复的密钥.用户';

在使用Audit.NET的AuditTrail实现中,如何逐月将数据摄取到AzureTableStorage?

如何在VS代码中为C#DotNet配置.json选项以调试内部终端的控制台应用程序

使用带有参数和曲面的注入失败(&Q;)

在.NET 7.0 API控制器项目中通过继承和显式调用基类使用依赖项注入

如何允许数组接受多个类型?

如何将%{v_扩展}转换为%{v_扩展}>>

在C#ASP.NET内核中使用INT AS-1进行控制器场景的单元测试

MSI无法将快捷方式添加到启动文件夹

类/值和日期的泛型方法

如何解决System.StackOverflowException:抛出System.StackOverflowException类型的异常.&# 39;生成随机代码时发生异常?

ASP.NET Core 8 Web API:如何添加版本控制?

使用LibraryImport在多个dll中导入相同的函数