我正在尝试使用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]}
我已按照说明here启用了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控制面板中也启用了管理SDK服务。
我尝试使用DriveService并成功列出/创建/删除文件没有任何问题,因此代码的身份验证部分应该没问题。我无法弄清楚还需要配置什么,或者我的代码是否有任何其他问题。
感谢您的帮助。
答案 0 :(得分:11)
如页面所述:
管理API客户端访问
开发人员可以向Google注册其网络应用程序和其他API客户端,以便启用访问权限 谷歌服务中的数据,如日历。你可以授权这些 注册客户可以访问您的用户数据,而无需用户单独提供同意或密码。了解更多
服务帐户需要根据用户的行为进行操作,因此在初始化客户端时,需要分配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
});
答案 1 :(得分: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: Users list。 有限制和配额。
答案 2 :(得分:1)
我们需要提供我们使用超级管理员或权限的服务ID才能传递此错误。
希望这会有所帮助。 -Venu Murthy
答案 3 :(得分: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();
}
}
}