Google analytics with web application Error

private static readonly IAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets
            {
                ClientId = "XXXXXXXXX",
                ClientSecret = "XXXXXXXXXXXX"
            },
            Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly, AnalyticsService.Scope.AnalyticsEdit },
            DataStore = new FileDataStore("Analytics.Auth.Store")//new FileDataStore("Drive.Api.Auth.Store")
        });

I am using above code for google console web application(Google Analytic) but it gives error System.UnauthorizedAccessException: Access to the path 'Analytics.Auth.Store' is denied.

Upvotes: 1

Views: 1048

Answers (2)

Rino Reji Cheriyan
Rino Reji Cheriyan

Reputation: 107

This is because you dont have write access to AppData folder on a Webserver and FileDataStore uses that folder by default.

You can use a different folder by giving full path as parameter

FileDataStore(string folder, bool fullPath = false)

sample implementation

static FileDataStore GetFileDataStore()
{
    var path = HttpContext.Current.Server.MapPath("~/App_Data/Drive.Api.Auth.Store");
    var store = new FileDataStore(path, fullPath: true);
    return store;
}

This way FileDataStore uses the App_Data folder of your application to write the TokenResponse. Dont forget to give write access to App_Data folder on the Webserver

You can read more about this at here and here

Upvotes: 1

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117016

FileDataStore stores the data in %AppData% on the pc. You need to make sure that you have access to that.

If you are planning on running this from a webserver you should not be using FileDataStore. You should create your own implementation of iDataStore, this will enable you to store the refresh tokens in the database.

Example:

 /// 
/// Saved data store that implements . 
/// This Saved data store stores a StoredResponse object.
/// 
class SavedDataStore : IDataStore
{
    public StoredResponse _storedResponse { get; set; }
    /// 
    /// Constructs Load previously saved StoredResponse.
    /// 
    ///Stored response
    public SavedDataStore(StoredResponse pResponse)
    {
        this._storedResponse = pResponse;
    }
    public SavedDataStore()
    {
        this._storedResponse = new StoredResponse();
    }
    /// 
    /// Stores the given value. into storedResponse
    /// .
    /// 
    ///The type to store in the data store
    ///The key
    ///The value to store in the data store
    public Task StoreAsync(string key, T value)
    {
        var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
        JObject jObject = JObject.Parse(serialized);
        // storing access token
        var test = jObject.SelectToken("access_token");
        if (test != null)
        {
            this._storedResponse.access_token = (string)test;
        }
        // storing token type
        test = jObject.SelectToken("token_type");
        if (test != null)
        {
            this._storedResponse.token_type = (string)test;
        }
        test = jObject.SelectToken("expires_in");
        if (test != null)
        {
            this._storedResponse.expires_in = (long?)test;
        }
        test = jObject.SelectToken("refresh_token");
        if (test != null)
        {
            this._storedResponse.refresh_token = (string)test;
        }
        test = jObject.SelectToken("Issued");
        if (test != null)
        {
            this._storedResponse.Issued = (string)test;
        }
        return TaskEx.Delay(0);
    }

    /// 
    /// Deletes StoredResponse.
    /// 
    ///The key to delete from the data store
    public Task DeleteAsync(string key)
    {
        this._storedResponse = new StoredResponse();
        return TaskEx.Delay(0);
    }

    /// 
    /// Returns the stored value for_storedResponse      
    ///The type to retrieve
    ///The key to retrieve from the data store
    /// The stored object
    public Task GetAsync(string key)
    {
        TaskCompletionSource tcs = new TaskCompletionSource();
        try
        {
            string JsonData = Newtonsoft.Json.JsonConvert.SerializeObject(this._storedResponse);
            tcs.SetResult(Google.Apis.Json.NewtonsoftJsonSerializer.Instance.Deserialize(JsonData));
        }
        catch (Exception ex)
        {
            tcs.SetException(ex);
        }
        return tcs.Task;
    }

    /// 
    /// Clears all values in the data store. 
    /// 
    public Task ClearAsync()
    {
        this._storedResponse = new StoredResponse();
        return TaskEx.Delay(0);
    }

    ///// Creates a unique stored key based on the key and the class type.
    /////The object key
    /////The type to store or retrieve
    //public static string GenerateStoredKey(string key, Type t)
    //{
    //    return string.Format("{0}-{1}", t.FullName, key);
    //}
}

Then instead of using FileDataStore you use your new SavedDataStore

//Now we load our saved refreshToken.
StoredResponse myStoredResponse = new StoredResponse(tbRefreshToken.Text);
// Now we pass a SavedDatastore with our StoredResponse.

credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
          new ClientSecrets { ClientId = "YourClientId", ClientSecret = "YourClientSecret" },
          new[] { AnalyticsService.Scope.AnalyticsReadonly},
          "user",
          CancellationToken.None,
           new SavedDataStore(myStoredResponse)).Result; }

Upvotes: 1

Related Questions