与C#中的Google Admin SDK集成

时间:2019-05-01 15:14:13

标签: c# google-api google-admin-sdk google-api-dotnet-client gsuite

我目前正在尝试通过C#与Google Admin SDK集成,以便我们可以通过自己的系统管理用户。但是,在运行项目时,出现错误:未经授权的客户端。

我已经通过超级管理员帐户完成的操作:

这是我正在使用的代码。

ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(_googleServiceSettings.Client_Email)
                {
                    ProjectId = _googleServiceSettings.Project_Id,
                    User = "superadmin@google.com",
                    Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser }
                }.FromPrivateKey(_googleServiceSettings.Private_Key));

            var service = new DirectoryService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = "Test API"
            });

            var request = service.Users.Get("user@google.com");
            var result = await request.ExecuteAsync();

我得到的全部错误是

  

执行请求时发生未处理的异常。   Google.Apis.Auth.OAuth2.Responses.TokenResponseException:错误:“ unauthorized_client”,说明:“客户端未经授权使用此方法检索访问令牌,或者客户端未获得所请求的任何范围的授权。”,Uri:“” < / p>

3 个答案:

答案 0 :(得分:4)

示例代码将显示有关用户的一些信息。

重要的是Google.Apis.Admin.Directory.directory_v1.Data.User

文档link

您的错误是由于未正确创建凭据引起的。通常,创建凭据时会出现范围问题。我假设您已为服务帐户正确设置了“域委托”。

我还假设您要模拟的用户是G Suite超级管理员。如果没有,您将看到service.Users.Get()的403错误。

文件service_account.json是您从Google控制台下载(或使用gcloud创建)的普通JSON文件。

用户user1@example.com是G Suite用户的电子邮件地址,将为其显示信息。

用户admin@example.com是G Suite超级管理员。

using Google.Apis.Auth.OAuth2;
using Google.Apis.Admin.Directory.directory_v1;
using Google.Apis.Admin.Directory.directory_v1.Data;
using Google.Apis.Services;
using System;
using System.IO;

// dotnet add package Google.Apis.Admin.Directory.directory_v1
// Tested with version 1.39.0.1505

// Google.Apis.Admin.Directory.directory_v1.Data.User
// https://developers.google.com/resources/api-libraries/documentation/admin/directory_v1/csharp/latest/classGoogle_1_1Apis_1_1Admin_1_1Directory_1_1directory__v1_1_1Data_1_1User.html

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Service Account with Domain-Wide delegation
            var sa_file = "service_account.json";

            // G Suite User to impersonate
            var user_email = "admin@example.com";

            // G Suite User to get information about
            var gs_email = "user1@example.com";

            // Scopes
            var scopes = "https://www.googleapis.com/auth/admin.directory.user";

            var credential = GoogleCredential.FromFile(sa_file)
                        .CreateScoped(scopes)
                        .CreateWithUser(user_email);

            // Create Directory API service.
            var service = new DirectoryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential
            });

            try {
                var request = service.Users.Get(gs_email);

                var result = request.Execute();

                Console.WriteLine("Full Name: {0}", result.Name.FullName);
                Console.WriteLine("Email:     {0}", result.PrimaryEmail);
                Console.WriteLine("ID:        {0}", result.Id);
                Console.WriteLine("Is Admin:  {0}", result.IsAdmin);
            } catch {
                Console.WriteLine("User not found.");
            }
        }
    }
}

答案 1 :(得分:3)

如果要使用服务帐户,可以使用以下代码进行身份验证。

String serviceAccountEmail = "yourserviceaccountmail";
public GmailService GetService(string user_email_address)
    {

        var certificate = new X509Certificate2(@"yourkeyfile.p12", 
"notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
                   new ServiceAccountCredential.Initializer(serviceAccountEmail)
                   {

                       User = user_email_address,
                       Scopes = new[] { GmailService.Scope.MailGoogleCom }
                   }.FromCertificate(certificate));

        GmailService service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = AppName,
        });

        return service;
    }

您可以列出使用此服务的用户。它为我工作。

您可以使用以下代码列出用户列表。 (使用DirectoryService)

public Users GetDirService()//UserList with DirectoryService
    {
        string Admin_Email = "yoursuperadminemail";
        string domain = "yourdomain.com";
        try
        {
            var certificate = new X509Certificate2(@"yourkeyfile.p12", "notasecret", X509KeyStorageFlags.Exportable);

            ServiceAccountCredential credentialUsers = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser },
                User = Admin_Email,
            }.FromCertificate(certificate));

            var serviceUsers = new DirectoryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credentialUsers,
                ApplicationName = AppName,
            });
            var listReq = serviceUsers.Users.List();
            listReq.Domain = domain;
            Users users = listReq.Execute();
            return users;
        }
        catch (Exception ex)
        {
            MessageBox.Show("your mail address must be super admin authorized.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
            return null;
        }

    }

答案 2 :(得分:1)

好,我已经解决了这个问题。

通过Google Portal中的安全设置添加以下作用域已解决了该问题。这很奇怪,因为他们自己的示例不需要添加此作用域,并且他们的文档没有说此方法是必需的。

https://www.googleapis.com/auth/admin.directory.group