0

I'm following the documentation from Google on how to create a user through the API but I cannot figure what I'm missing.

This is the code I'm using:

    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)
        {
        }
    }

At this point I always get:

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

I've enabled the Admin SDK API and created a service account, which is the one I'm using here.

vmasanas
  • 503
  • 1
  • 7
  • 18
  • possible duplicate of [Google Admin SDK Unable to Create User - Exception 403 Forbidden](http://stackoverflow.com/questions/20956767/google-admin-sdk-unable-to-create-user-exception-403-forbidden) – Benjamin Diele Aug 05 '14 at 08:09
  • Note I am not even sure you can do this. Assuming you could the service account would need access to what ever domain it is you are trying to add users to. You may be able to take the service account email address and add that as an admin giving it the permissions needed to add users. – Linda Lawton - DaImTo Aug 05 '14 at 08:10

1 Answers1

1

The trick to the above code is that I forgot to add the admin account email on the crendentials.

This code will fix the problem:

           ServiceAccountCredential credential = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
           {
               Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser },
               User = "admin_account_email@domain.com"
           }.FromCertificate(certificate));
vmasanas
  • 503
  • 1
  • 7
  • 18