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

标签 c# asp.net-mvc oauth-2.0 google-api google-oauth

我实现了我的自定义 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/

相关文章:

c# - 当轮廓可以撕裂时,如何检测简单形状(使用emgu cv)?

c# - 不同 K 和 Volume 之间的 K-Dop 碰撞

c# - 执行强类型 ASP.NET MVC session 的更好方法

asp.net - 使用 ASP.net 检测 iPad

ios - Strava alamofire token

c# - 具有 Multi-Tenancy 数据访问的 Web API 身份验证

c# - 我如何捕获从字符串解析的 int 中的错误?

c# - 如何使用 LINQ to SQL 和 DbLinq 选择空值?

c# - 从 MVC 中的 Controller 方法获取属性标记?

testing - Protractor - 测试 Oauth2 时切换到 facebook 登录屏幕