谷歌云端硬盘API - 自定义IDataStore实体框架
问题描述:
我实现我的自定义IDataStore
,这样我可以存储在我的数据库,而不是默认的实现,这是保存在%APPDATA%以内文件系统最终用户令牌。谷歌云端硬盘API - 自定义IDataStore实体框架
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;
}
}
控制器
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
不是令牌响应,而是字符串。此外,密钥前缀为“oauth_”。
所以我认为我应该返回一个不同的重定向结果,但我不知道该返回什么。
我得到的错误是:Google.Apis.Auth.OAuth2.Responses.TokenResponseException:错误: “国家是无效的”,说明: “” 乌里: “”
感谢您的帮助
答
我不完全确定你为什么不工作,但这是我使用的代码的副本。满级都可以在这里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;
}
答
的API存储(至少)两个值,发现您的IDataStore
。以下是授权过程看起来像一个空IDataStore的观点(注意这行设置一个值,该行得到值):
Getting IDataStore value: MyKey <= null
Setting IDataStore value: oauth_MyKey => "http://localhost..."
Setting IDataStore value: MyKey => {"access_token":"...
Getting IDataStore value: oauth_MyKey <= "http://localhost..."
Getting IDataStore value: MyKey <= {"access_token":"...
起初,API试图找到一个存储为access_token
,但数据存储中没有(仅返回null
),API开始授权过程。 “oauth _...”键是API在此过程中需要的一些状态信息,通常在检索之前设置(根据我的经验)。
但是,如果您的IDataStore
从未收到带有“oauth_ ..”键的值,并因此没有任何返回值,则只需返回null
,API将在需要时创建一个新值。
嗨。 Mine也在工作。但是,在“StoreAsync”之后的初始重定向(用于授权访问其谷歌驱动器)中,调用GetAsync并且键值为*[email protected]*。所以这是我得到的错误。我不确定你的项目是否与我一样是MVC ......这个问题可能与此有关。我将用“Controller”代码编辑我的问题。 – 2014-12-06 14:59:36