gpt4 book ai didi

c# - Google Drive Api - 带有 Entity Framework 的自定义 IDataStore

转载 作者:可可西里 更新时间:2023-11-01 08:29:32 24 4
gpt4 key购买 nike

我实现了我的自定义 IDataStore这样我就可以将最终用户 token 存储在我的数据库中,而不是默认实现,默认实现保存在 FileSystem 中的 %AppData%。

public class GoogleIDataStore : IDataStore
{
...

public Task<T> GetAsync<T>(string key)
{
TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();

var user = repository.GetUser(key.Replace("oauth_", ""));

var credentials = repository.GetCredentials(user.UserId);

if (key.StartsWith("oauth") || credentials == null)
{
tcs.SetResult(default(T));
}
else
{
var JsonData = Newtonsoft.Json.JsonConvert.SerializeObject(Map(credentials));
tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize<T>(JsonData));
}
return tcs.Task;
}
}

Controller

public async Task<ActionResult> AuthorizeDrive(CancellationToken cancellationToken)
{
var result = await new AuthorizationCodeMvcApp(this, new GoogleAppFlowMetadata()).
AuthorizeAsync(cancellationToken);

if (result.Credential == null)
return new RedirectResult(result.RedirectUri);

var driveService = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "My app"
});

//Example how to access drive files
var listReq = driveService.Files.List();
listReq.Fields = "items/title,items/id,items/createdDate,items/downloadUrl,items/exportLinks";
var list = listReq.Execute();

return RedirectToAction("Index", "Home");
}

问题发生在重定向事件上。在第一次重定向之后它工作正常。

我发现重定向事件有些不同。在重定向事件中 T不是 token 响应,而是字符串。此外, key 以“oauth_”为前缀。

所以我假设我应该在重定向时返回不同的结果,但我不知道要返回什么。

我得到的错误是:Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"State is invalid", Description:"", Uri:""

Google 源代码引用 https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis.DotNet4/Apis/Util/Store/FileDataStore.cs?r=eb702f917c0e18fc960d077af132d0d83bcd6a88

https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis.Auth/OAuth2/Web/AuthWebUtility.cs?r=eb702f917c0e18fc960d077af132d0d83bcd6a88

谢谢你的帮助

最佳答案

我不确定为什么你的代码不起作用,但这是我使用的代码的副本。完整的类(class)可以在这里找到 DatabaseDatastore.cs

/// <summary>
/// Returns the stored value for the given key or <c>null</c> if the matching file (<see cref="GenerateStoredKey"/>
/// in <see cref="FolderPath"/> 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>
public Task<T> GetAsync<T>(string key)
{
//Key is the user string sent with AuthorizeAsync
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key MUST have a value");
}
TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();


// Note: create a method for opening the connection.
SqlConnection myConnection = new SqlConnection("user id=" + LoginName + ";" +
@"password=" + PassWord + ";server=" + ServerName + ";" +
"Trusted_Connection=yes;" +
"database=" + DatabaseName + "; " +
"connection timeout=30");
myConnection.Open();

// Try and find the Row in the DB.
using (SqlCommand command = new SqlCommand("select RefreshToken from GoogleUser where UserName = @username;", myConnection))
{
command.Parameters.AddWithValue("@username", key);

string RefreshToken = null;
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
RefreshToken = myReader["RefreshToken"].ToString();
}

if (RefreshToken == null)
{
// we don't have a record so we request it of the user.
tcs.SetResult(default(T));
}
else
{

try
{
// we have it we use that.
tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize<T>(RefreshToken));
}
catch (Exception ex)
{
tcs.SetException(ex);
}

}
}

return tcs.Task;
}

关于c# - Google Drive Api - 带有 Entity Framework 的自定义 IDataStore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27254339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com