nik*_*619 7 c# google-api google-api-dotnet-client google-admin-sdk 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();
Run Code Online (Sandbox Code Playgroud)
我得到的全部错误是
执行请求时发生未处理的异常。Google.Apis.Auth.OAuth2.Responses.TokenResponseException:错误:“ unauthorized_client”,说明:“客户端未经授权使用此方法检索访问令牌,或者客户端未获得所请求的任何范围的授权。”,Uri:“”
将打印有关用户的一些信息的示例代码。
重要的项目是类 Google.Apis.Admin.Directory.directory_v1.Data.User
文档链接。
您的错误是由于未正确创建凭据引起的。通常,创建凭据时范围存在问题。我假设您已为服务帐户正确设置了域范围委派。
我还假设您要冒充的用户是 G Suite 超级管理员。如果没有,您将看到 403 错误service.Users.Get()。
该文件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.");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想使用服务帐户,您可以使用以下代码进行身份验证。
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;
}
Run Code Online (Sandbox Code Playgroud)
您可以列出使用此服务的用户。它对我有用。
您可以使用以下代码列出用户列表。(使用目录服务)
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;
}
}
Run Code Online (Sandbox Code Playgroud)