标签: google-api-dotnet-client

如何使用服务帐户对Google v3 api进行身份验证

我在此处遵循示例代码:https: //code.google.com/p/google-api-dotnet-client/wiki/OAuth2#Service_Accounts

授权失败:DotNetOpenAuth.Messaging.ProtocolException:发送直接消息或获取响应时出错.

内部异常是System.Net.WebException:远程服务器返回错误:(400)错误请求.响应正文为空,响应URI为https://accounts.google.com/o/oauth2/token.

在下面的响应中,您将看到特定错误是invalid_grant.

这是我的代码:

var certificate = new X509Certificate2(CertificatePath, "notasecret", X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
    {
        ServiceAccountId = "<...>@developer.gserviceaccount.com",
        Scope = CalendarService.Scopes.Calendar.GetStringValue()
    };

var authenticator = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);

var calendarService =
    new CalendarService(new BaseClientService.Initializer()
        {
            Authenticator = authenticator
        });

var eventList = calendarService.Events.List("<id of the calendar>").Execute();
Run Code Online (Sandbox Code Playgroud)

证书和ServiceAccountId是正确的.我有三重检查,并且好的措施重新生成了证书.在用于创建服务帐户的Google开发者帐户的API控制台中启用了Google Calendar API.此帐户不属于Google Apps域.

我还使用指定的AssertionFlowClient的ServiceAccountUser属性对此进行了测试.我现在认为这是必需的 - 在我使用手动创建的JWT成功测试CalendarService时(请参阅下面的手动创建OAuth令牌工程),当prn属性未包含在prn属性中时,我在尝试创建令牌时收到404错误声明(即不包括ServiceAccountUser).

Google Apps域配置

在Google Apps域中,我已授予对此服务帐户日历的访问权限.

客户名称:[snip] .apps.googleusercontent.com

API范围:

安装了NuGet包

  • Google.Apis(1.5.0-beta)
  • Google.Apis.Calendar.v3(1.5.0.59-beta)
  • Google.Apis.Authentication(1.5.0-beta)

请求和响应

POST https://accounts.google.com/o/oauth2/token …
Run Code Online (Sandbox Code Playgroud)

.net google-calendar-api jwt google-oauth google-api-dotnet-client

9
推荐指数
1
解决办法
5099
查看次数

无法使用Google Directory API Admin SDK列出用户

我正在尝试使用AdminService来管理我的域的用户和组,但我遇到了一个简单的请求来获取我的域的所有用户.C#中有代码:

public Users GetAllUsers()
{
    var provider = new AssertionFlowClient(
        GoogleAuthenticationServer.Description,
        new X509Certificate2(privateKeyPath, keyPassword, X509KeyStorageFlags.Exportable))
    {
        ServiceAccountId = serviceAccountEmail,
        Scope = AdminService.Scopes.AdminDirectoryUser.GetStringValue()
    };

    var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);

    m_serviceGroup = new AdminService(new BaseClientService.Initializer()
    {
        Authenticator = auth,
    });

    var request = m_serviceUser.Users.List();
    request.Domain = m_domainName;
    return request.Fetch();
}
Run Code Online (Sandbox Code Playgroud)

当Fetch()表示:我得到一个异常:

Code: 403    
Message: Not Authorized to access this resource/api 
Error: {Message[Not Authorized to access this resource/api] Location[ - ] Reason[forbidden] Domain[global]}
Run Code Online (Sandbox Code Playgroud)

我按照此处的说明启用了API访问权限,并在域控制面板中授权了我的服务帐户:

[Security]->[Advanced Setting]->[Authentication]->[Manage third party …
Run Code Online (Sandbox Code Playgroud)

c# google-api google-api-dotnet-client google-admin-sdk

8
推荐指数
1
解决办法
7982
查看次数

.NET Google api 1.7 beta使用刷新令牌进行身份验证

我一直在关注Oauth .Net Google Apis,以便通过OAuth进行身份验证并使用Google驱动Apis.

具体来说,我想使用我已经存储的刷新令牌,以便使用它来实例化GoogleDrive服务.

我找到了像https://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.SimpleOAuth2/Program.cs?repo=samples这样的示例

这似乎使用"GoogleWebAuthorizationBroker.AuthorizeAsync",但我不确定如何使用刷新令牌而不是客户端的秘密,你似乎在这个例子中提供它.

c# google-drive-api google-oauth google-api-dotnet-client

8
推荐指数
1
解决办法
6097
查看次数

我在哪里可以找到ServiceAccountCredential

我在使用asp.net c#的google api工作,我的目标是使用服务帐户访问google api.

我已导入所有需要的dll以创建服务帐户以访问管理员功能(admin sdk).

但我找不到ServiceAccountCredential.

我如何在我的项目中实现这一点?

c# asp.net google-api google-oauth google-api-dotnet-client

8
推荐指数
2
解决办法
1万
查看次数

GoogleWebAuthorizationBroker.AuthorizeAsync冻结

我有一个C#.net网络应用程序,用于将视频上传到Youtube.这工作大约6个月前,但现在已停止工作.当我在本地计算机上通过Visual Studio启动我的网站时,以下代码会挂起:

     UserCredential credential;
    using (var auth_stream = new FileStream(Server.MapPath("~/YouTube/client_secrets.json"), FileMode.Open, FileAccess.Read))
    {
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(auth_stream).Secrets,
            // This OAuth 2.0 access scope allows an application to upload files to the
            // authenticated user's YouTube channel, but doesn't allow other types of access.
            new[] { YouTubeService.Scope.YoutubeUpload },
            "user",
            CancellationToken.None
        );
    }
Run Code Online (Sandbox Code Playgroud)

在查看堆栈溢出的其他帖子之后我也尝试了以下内容:

     UserCredential credentialS;
     using (var auth_stream = new FileStream(Server.MapPath("~/YouTube/client_secrets.json"), FileMode.Open, FileAccess.Read))
     {
         credentialS = await GoogleWebAuthorizationBroker.AuthorizeAsync(
             new ClientSecrets
             {
                 ClientId = "blahblah-myDetailsBlahBLah.apps.googleusercontent.com",
                 ClientSecret = "myClientSecret",
             },
             // This …
Run Code Online (Sandbox Code Playgroud)

c# google-api youtube-api oauth-2.0 google-api-dotnet-client

8
推荐指数
1
解决办法
3559
查看次数

谷歌日历Api在本地工作正常但不提高其在服务器上的身份验证

我创建了一个项目console.developers.google.com使用Google Calendar API.我们需要生成凭证并选择应用程序类型

对于Localhost和应用程序类型,other以下是可行的Json.

{
    "installed": {
    "client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
    "project_id": "xxxxxx-00000",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "xxxxxxxxxxxx",
    "redirect_uris": [ "urn:ietf:wg:oauth:2.0:oob", "http://localhost" ]
    }
}
Run Code Online (Sandbox Code Playgroud)

对于Web Application服务器上的主机应用程序类型少数参数具有不同的值,Json如下所示.

{
    "web": {
    "client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
    "project_id": "xxxxxxxx-99999",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "xxxxxxxxxxxxxxxxxxxxxxx",
    "redirect_uris": [ "http://demo.mydemo.com" ],
    "javascript_origins": [ "http://demo.mydemo.com" ]
    }
}
Run Code Online (Sandbox Code Playgroud)

此处,当用户(仅限已集成Google日历的用户)尝试创建活动时,Google应同意使用哪个Google帐户,并要求在重定向到重定向页面之前阅读个人数据.在同意后,它将在所选谷歌帐户的日历中添加提供的数据.问题是它没有将用户重定向到Oauth身份验证即The Consent Screen.

同意屏幕的图像 任何人都可以帮我解决这个问题吗?

错误如下

System.AggregateException: One or more errors occurred. …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc google-calendar-api google-oauth google-api-dotnet-client

8
推荐指数
1
解决办法
1290
查看次数

Google API V 3.0 .Net库和Google OAuth2如何处理刷新令牌

在我的应用程序中,我使用Google API V 3.0 .Net库与Google OAuth2同步Google日历和Outlook日历.我使用下面的代码来获取Google.Apis.Calendar.v3.CalendarService服务对象.在身份验证期间,我存储了Json文件,并从中请求了Google.Apis.Auth.OAuth2.UserCredential对象.

private Google.Apis.Auth.OAuth2.UserCredential GetGoogleOAuthCredential()
{
    GoogleTokenModel _TokenData = new GoogleTokenModel();
    String JsonFilelocation = "jsonFileLocation;
    Google.Apis.Auth.OAuth2.UserCredential credential = null;
    using (var stream = new FileStream(JsonFilelocation, FileMode.Open,
                    FileAccess.Read))
    {
        Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store";
        credential = Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(
        Google.Apis.Auth.OAuth2.GoogleClientSecrets.Load(stream).Secrets,
        new[] { Google.Apis.Calendar.v3.CalendarService.Scope.Calendar },
        "user",
        CancellationToken.None,
        new FileDataStore("OGSync.Auth.Store")).Result;
    }
    return credential;
}
Run Code Online (Sandbox Code Playgroud)

请求服务对象代码是:

Google.Apis.Calendar.v3.CalendarService _V3calendarService = new Google.Apis.Calendar.v3.CalendarService(new Google.Apis.Services.BaseClientService.Initializer()
{
HttpClientInitializer = GetGoogleOAuthCredential(),
ApplicationName = "TestApplication",
});
Run Code Online (Sandbox Code Playgroud)

上面的代码可以很好地获取Calendarservice对象.我的问题是,我的Json文件有刷新和访问令牌.当访问令牌过期时,上述代码如何处理刷新令牌以获取服务?因为我需要经常调用Calendarservice对象,所以我喜欢为calenderService对象实现单例模式.如何在不经常调用GetGoogleOAuthCredential的情况下获取Calendarservice?任何帮助/指导表示赞赏.

c# google-calendar-api google-api google-oauth google-api-dotnet-client

7
推荐指数
2
解决办法
1万
查看次数

MVC应用中的Google OAuth访问令牌到期?

我按照此处的说明使用Google Oauth2编写了一个MVC应用程序:https: //developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web_applications

我有访问令牌到期的问题.当访问令牌过期时,我在调用Google API时遇到异常:"访问令牌已过期,但我们无法刷新它"

初始身份验证是两种迭代机制:

第一次迭代AuthorizeAsync返回结果为空Credential,并填充RedirectUri:

因此,创建的授权URL是:

https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=MYCLIENTID&redirect_uri=http:%2F%2Flocalhost%2FHomepage%2FAuthCallback%2FIndexAsync&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar https:%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly&state=http:%2F%2Flocalhost%2FHomepage%2F95419199
Run Code Online (Sandbox Code Playgroud)

请注意,access_type = offline存在.所以我也应该恢复刷新令牌(不会发生).

在此输入图像描述

第二次迭代 - AuthorizeAsync返回带有填充的凭据且空RedirectUri的结果:

问题1 - 此时RefreshToken是否应该为空?

在此输入图像描述

记住结果,因为它被定义为静态的.

下一个请求 - 需要result.Credential调用Google Calendar API的日历操作:

问题2 - 如果访问令牌在那一刻到期(为了测试我只设置ExpiresInSeconds = 0),我调用RefreshTokenAsync方法,但它总是返回false!为什么?我在这里错过了什么?

当RefreshTokenAsync返回false时,处理什么是正确的方法?当前RedirectResult(result.RedirectUri)命令将失败,因为result.RedirectUri为null.

在此输入图像描述

asp.net-mvc google-oauth google-api-dotnet-client

7
推荐指数
1
解决办法
4220
查看次数

将Google API .NET客户端与现有访问令牌一起使用

用例如下:移动应用程序正在通过Google对用户进行身份验证,在某些时候,我们需要将用户的视频发布到他的YouTube帐户; 出于实际原因,实际的发布应该由后端(已经存储在那里的大文件)完成.

由于用户已经通过应用进行了身份验证,因此应用只会将用户的访问令牌发送到后端.现在,我的目标是找到如何将此访问令牌与.NET客户端一起使用...到目前为止,我已尝试UserCredential从该访问令牌创建实例,但这似乎不起作用.此外,我们不需要提供所有令牌刷新逻辑,UserCredential因为我们知道此时访问令牌是有效的.

任何帮助将不胜感激,谢谢!

c# google-api google-api-dotnet-client

7
推荐指数
1
解决办法
298
查看次数

如何上传/转换 *.docx 为 google 文档?谷歌云端硬盘 API v3

我在上传 microsoft/libre Office 文档以通过 Google Apps 进行编辑时遇到问题。对于电子表格,它可以正常工作,但对于文档则不然。

当我上传扩展名为 *.odt、*.docx 的文件时,我可以通过 Google 云端硬盘上的 google 查看器查看内容,但是当我单击文档顶部的“使用按钮进行编辑”时,Google 云端硬盘会创建一个具有相同内容和名称的新文件但我没有关于描述中的原始文件 ID 或任何能力的信息。有什么想法如何上传准备在线编辑的文档吗?

  private async Task<string> UploadFileToGoogleDrive(string filePath, GoogleDriveFile file)
    {
        var fileData = new Google.Apis.Drive.v3.Data.File()
        {
            Name = file.Name,
            MimeType = file.MimeType

        };
        if (!String.IsNullOrEmpty(file.ParentId))
            fileData.Parents = new List<string>() { file.ParentId };

        FilesResource.CreateMediaUpload request;

        using (var stream = new FileStream(filePath, FileMode.Open))
        {
             request = _driveService.Files.Create(fileData, stream, StringEnum.GetStringValue(file.FileContent));
             request.Fields = "id";

             var uploadProgress = await request.UploadAsync();
             if (uploadProgress.Exception != null)
                 throw uploadProgress.Exception; 
        }
        return request.ResponseBody.Id;
    } …
Run Code Online (Sandbox Code Playgroud)

c# google-api google-drive-api google-api-dotnet-client

7
推荐指数
1
解决办法
3013
查看次数