Google анализ с уеб приложение Грешка

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")
        });

Използвам горния код за уеб приложение на конзолата на Google (Google Analytic), но той дава грешка System.UnauthorizedAccessException: Достъпът до пътя „Analytics.Auth.Store“ е отказан.


person Muhammad Sanaan Chattha    schedule 22.04.2014    source източник


Отговори (2)


FileDataStore съхранява данните в %AppData% на компютъра. Трябва да сте сигурни, че имате достъп до това.

Ако планирате да стартирате това от уеб сървър, не трябва да използвате FileDataStore. Трябва да създадете своя собствена реализация на iDataStore, това ще ви позволи да съхранявате токените за опресняване в базата данни.

Пример:

 /// 
/// 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);
    //}
}

Тогава вместо да използвате FileDataStore, вие използвате новия си 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; }
person DaImTo    schedule 22.04.2014
comment
какво е съхраненият отговор?? - person Muhammad Sanaan Chattha; 22.04.2014

Това е така, защото нямате достъп за запис в папката AppData на уеб сървър и FileDataStore използва тази папка по подразбиране.

Можете да използвате друга папка, като посочите пълния път като параметър

FileDataStore(string folder, bool fullPath = false)

примерна реализация

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

По този начин FileDataStore използва папката App_Data на вашето приложение, за да напише TokenResponse. Не забравяйте да дадете достъп за запис в папката App_Data на уеб сървъра

Можете да прочетете повече за това тук и тук

person Rino Reji Cheriyan    schedule 11.11.2014