Google API .NET 抛出 UnauthorizedAccessException

Google API .NET Throws UnauthorizedAccessException

我正在尝试使用 Nuget 包 Google 分发来与他们的 Google Calendar V3 API 进行交互,详见 official tutorial here.

这是我的调用代码(全部包含在静态包装器中 class 我写的调用 GoogleCalendarAPI):

// The file path the API credentials are stored in.
private static readonly string credentialsFilePath = "Assets/Config/credentials.json";

// The file path the authenticated token for API access is stored in.
private static readonly string authTokenFilePath = ApplicationData.Current.LocalFolder.Path + "\token.json";

// The scopes within the API the app is accessing.
private static readonly string[] scopes = { CalendarService.Scope.CalendarReadonly };

// The name of the application to present to the API.
private static readonly string applicationName = "Minimalism Calendar";

// A cache of the authorized user credential for the Google Calendar API.
private static UserCredential credential = null;

public static async Task AuthorizeAsync()
{
    // This function is adapted from Google's tutorial: https://developers.google.com/calendar/quickstart/dotnet

    using (FileStream stream = new FileStream(
        GoogleCalendarAPI.credentialsFilePath, FileMode.Open, FileAccess.Read))
    {
        try
        {
            // This output line provides the correct (expected) output.
            System.Diagnostics.Debug.WriteLine("the path is: " + GoogleCalendarAPI.authTokenFilePath);

            GoogleCalendarAPI.credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                GoogleCalendarAPI.scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(GoogleCalendarAPI.authTokenFilePath, true));

            // This output line is never reached
            System.Diagnostics.Debug.WriteLine("B");
        }
        catch (Exception e)
        {
            // This error is NOT thrown.
            System.Diagnostics.Debug.WriteLine("ERROR: " + e.Message);
        }
    }
}

当我 运行 代码时,我从 Windows 得到以下对话框:

根据此对话框的标题,以及我的输入文件路径似乎有效且正确的事实...我只能得出结论,错误来自 Google 的 GoogleWebAuthorizationBroker.AuthorizeAsync() 方法?

我注意到“.NET”教程专门针对 控制台应用程序,而不是 UWP 应用程序。前者的文件访问限制要少得多...所以也许 Google 在此方法中所做的对前者有效但对后者无效?

同样重要的是要注意:发生这种情况时,Visual Studio 控制台不会显示任何错误或错误消息。

有什么想法吗?

UWP 在访问文件系统时有限制。默认情况下,UWP 应用程序只能访问某些特定位置。另一件事是 UWP 不允许使用 Path 访问文件。如果你想使用Path获取文件,你需要启用broadFileSystemAccess能力并且只使用Windows.Storage Namespace. For more detailed information, please check: File access permissions

在代码中,我注意到您有一个参数 new FileDataStore(GoogleCalendarAPI.authTokenFilePath, true))。这应该是这种行为的原因。 Google API 正在尝试使用路径访问文件。

目前,没有其他方法可以绕过 UWP 应用程序中的 UWP 文件限制。

针对您的情况的一个可能的解决方案是,您可以先创建一个控制台应用程序,然后在控制台应用程序中实现您想要的 Google 功能。之后,您可以将控制台应用程序和 UWP 应用程序一起打包到桌面桥应用程序中。所以当你想调用 Google 函数时,你可以让 UWP 应用程序启动控制台应用程序。