Я пытаюсь создать пользователя с использованием клиентских библиотек C# и google-admin-directory_v1-rev24-csharp-1.7.0-beta, но я все равно получаю исключение:Google Admin SDK Не удалось создать пользователя - исключение 403 Запрещено
Google.GoogleApiException was unhandled
HResult=-2146233088
Message=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]
]
Source=Google.Apis
ServiceName=admin
StackTrace:
at Google.Apis.Requests.ClientServiceRequest`1.Execute() in c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug \output\default\Src\GoogleApis\Apis\Requests\ClientServiceRequest.cs:line 102
at ConsoleApplication1.Program.Main(String[] args) in c:\Users\darin.BASEHEX\Documents\Visual Studio 2013\Projects \ConsoleApplication1\ConsoleApplication1\Program.cs:line 55
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Я начал с созданием проекта в консоли разработчика, под страницей APIs настройки я включил ADMIN SDK под страницей Учетных данных я создал учетную запись службы и загрузить сертификат p12.key, я заполнил Экран согласия, а затем я перешел на страницу «Безопасность» в консоли администратора, выбрал вкладку «Предварительный», выбрал «Управление доступом стороннего клиента OAuth», вставил в идентификатор клиента из созданной мной учетной записи службы и присвоил область https://www.googleapis.com/auth/admin.directory.user/. Исключение поднимается на линии:
User results = service.Users.Insert(newuserbody).Execute();
Полная программа на C# ниже.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Admin.Directory.directory_v1;
using Google.Apis.Admin.Directory.directory_v1.Data;
using Google.Apis.Services;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String serviceAccountEmail = "A bunch of alpha [email protected]";
var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser },
User = "[email protected]" <-------- Added ADMIN User to fix
}.FromCertificate(certificate));
// Create the service.
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "User Provisioning",
});
User newuserbody = new User();
UserName newusername = new UserName();
newuserbody.PrimaryEmail = "[email protected]";
newusername.GivenName = "Bob";
newusername.FamilyName = "Bacon";
newuserbody.Name = newusername;
newuserbody.Password = "iambacon";
User results = service.Users.Insert(newuserbody).Execute();
Console.WriteLine("Press any key to continue!");
Console.ReadKey();
}
}
}
Я чувствую, что это что-то действительно просто. Я упускаю, однако у меня не осталось никаких идей о том, на что смотреть. Любая помощь будет принята с благодарностью!
Вы уверены, что в этом проекте включен SDK администратора? В общем случае код статуса 403 является результатом отказа от API, поэтому, пожалуйста, убедитесь, что он включен. – peleyal
Привет, Пелей, Да, проект ADMIN включен для проекта. – user3149930