使用Google Web Authorization Broker将用户凭据保存到数据库



我已经成功地使用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);
}
}

然后是我的google凭据模型

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

对这一切还很陌生,但这就是我所拥有的,我认为我在正确的方向上,从我的理解,但也许一些更有知识的人可以看看,引导我走上正确的道路。

构造函数接受一个连接字符串。

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 h1> /html>

最新更新