Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Drive Api - Custom IDataStore with Entity Framework

I implemented my custom IDataStore so that I can store End User Tokens on my database instead of the default implementation, which is saved on FileSystem within %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");
}

The issue happens on the redirect event. After that first redirect it works fine.

I found out that something is different on the redirect event. On the redirect event the T is not a Token Response, but a string. Also, the key is prefixed with "oauth_".

So I assume that I should return a different result on the redirect, but I have no clue what to return.

The error I get is : Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"State is invalid", Description:"", Uri:""

Google Source Code Reference 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

Thanks for your help

like image 755
Hugo Hilário Avatar asked Dec 02 '14 16:12

Hugo Hilário


1 Answers

I am not exactly sure why yours isnt working but this is a copy of the code i use. The full class can be found here 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;
        }
like image 166
DaImTo Avatar answered Oct 24 '22 08:10

DaImTo