我按照Google提供的有关如何通过API创建用户的文档,但我无法弄清楚我错过了什么。
这是我使用的代码:
string SERVICE_ACCOUNT_PKCS12_FILE_PATH = @"myfile.p12";
string SERVICE_ACCOUNT_EMAIL = "...@developer.gserviceaccount.com";
void CreateUser()
{
var certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
{
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser }
}.FromCertificate(certificate));
var service = new DirectoryService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "apitest"
});
var user = new Google.Apis.Admin.Directory.directory_v1.Data.User()
{
Name = new Google.Apis.Admin.Directory.directory_v1.Data.UserName()
{
GivenName = txtName.Text,
FamilyName = txtFamilyName.Text
},
Password = txtPasword.Text,
PrimaryEmail = txtEmail.Text
};
try
{
var result = service.Users.Insert(user).Execute();
}
catch (Exception ex)
{
}
}
此时我总是得到:
Google.Apis.Requests.RequestError
Not Authorized to access this resource/api [403]
Errors [
Message[Not Authorized to access this resource/api] Location[ - ] Reason[forbidden] Domain[global]
]
我已启用Admin SDK API并创建了一个服务帐户,这是我在这里使用的帐户。
答案 0 :(得分:1)
上述代码的诀窍是我忘了在crendentials上添加管理员帐户电子邮件。
此代码将解决问题:
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
{
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser },
User = "admin_account_email@domain.com"
}.FromCertificate(certificate));