9

我正在尝试使用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();
}

当 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]}

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

[Security]->[Advanced Setting]->[Authentication]->[Manage third party OAuth Client access]

范围:

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

API 控制面板中也启用了 Admin SDK 服务。

我尝试了使用DriveService的代码并成功列出/创建/删除文件没有任何问题,因此代码的身份验证部分应该没问题。我不知道还需要配置什么,或者我的代码是否还有其他问题。

谢谢你的帮助。

4

4 回答 4

11

如页面所述:

管理 API 客户端访问

开发人员可以向 Google 注册他们的 Web 应用程序和其他 API 客户端,以便能够访问 Google 服务(如日历)中的数据。您可以授权这些注册客户访问您的用户数据,而无需您的用户单独同意或提供他们的密码。学到更多

服务帐户需要根据用户的行为进行操作,因此在初始化客户端时需要分配 ServiceAccountUser。

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

编辑: AssertionFlowClient 已弃用,以下应该可以工作:

var cert = new X509Certificate2(privateKeyPath, keyPassword, X509KeyStorageFlags.Exportable);
var serverCredential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            Scopes = new []{DirectoryService.Scope.AdminDirectoryUser},
            User = domainManagerAccountEmail
        }.FromCertificate(cert));
var dirService = new DirectoryService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = serverCredential
        });
于 2013-06-11T08:25:43.977 回答
2

这段代码对我有用


static void GettingUsers()
{ 
  String serviceAccountEmail = "xxxxxxx@developer.gserviceaccount.com";
  var certificate = new X509Certificate2(@"xxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
  ServiceAccountCredential credential = new ServiceAccountCredential(
  new ServiceAccountCredential.Initializer(serviceAccountEmail)
  {
  Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser},
  User = "your USER",  
  }.FromCertificate(certificate));
  var service = new DirectoryService(new BaseClientService.Initializer()
  {
  HttpClientInitializer = credential,
  ApplicationName = "name of your app",
  });

  var listReq = service.Users.List();
  listReq.Domain = "your domain";
  Users allUsers = listReq.Execute();
  int counter = 0;
  foreach(User myUser in allUsers.UsersValue){
    Console.WriteLine("*" + myUser.PrimaryEmail);
     counter++;
}

Console.WriteLine(counter);
Console.ReadKey();

有关更多信息,请查看Directory API:用户列表。有限制和配额。

于 2014-02-19T19:22:36.510 回答
1

我们需要提供我们正在使用超级管理员的服务 ID 或正确的权限才能通过此错误。

希望这可以帮助。-维努·穆尔蒂

于 2013-08-13T05:28:28.070 回答
0

为我工作。

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 Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace ConsoleApplication1
{



    class Program
    {
        static string[] Scopes = { DirectoryService.Scope.AdminDirectoryUserReadonly};
        static string ApplicationName = "API G Suite implementation guid by amit";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials1/admin-directory_v1-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

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

            ////// Define parameters of request.
            UsersResource.ListRequest request = service.Users.List();
            request.Customer = "my_customer";
            request.MaxResults = 10;
            request.OrderBy = UsersResource.ListRequest.OrderByEnum.Email;

            ////// List users.
            IList<User> users = request.Execute().UsersValue;
            Console.WriteLine("Users:");
            if (users != null && users.Count > 0)
            {
               foreach (var userItem in users)
              {
                   Console.WriteLine("{0} ({1})", userItem.PrimaryEmail,
                       userItem.Name.FullName);
               }
            }
            else
            {
               Console.WriteLine("No users found.");
            }
            Console.Read();


        }
    }
}
于 2017-02-13T09:31:59.793 回答