C# Google API for requesting a list of users returns "badRequest"

157 views Asked by At

I have been looking for information on this for a couple days now. I believe I have everything relevant to the API set up correctly for access but I keep getting this error: The service admin has thrown an exception.

HttpStatusCode is BadRequest.
Google.Apis.Requests.RequestError
Bad Request [400]
Errors [
        Message[Bad Request] Location[ - ] Reason[badRequest] Domain[global]
]

Google.GoogleApiException: The service admin has thrown an exception. HttpStatusCode is BadRequest. Bad Request
   at Google.Apis.Requests.ClientServiceRequest`1.ParseResponse(HttpResponseMessage response)
   at Google.Apis.Requests.ClientServiceRequest`1.ExecuteAsync(CancellationToken cancellationToken)
   at Google.Apis.Requests.ClientServiceRequest`1.ExecuteAsync()

My method that runs the code:

string[] googleScopes = {DirectoryService.Scope.AdminDirectoryUser};
public async Task connectToGoogle()
        {
            try
            {
                GoogleCredential credential = GoogleCredential.FromFile(googleTokenPath).CreateScoped(googleScopes);//.CreateWithUser(googleAdminEmail);
                
                
                var service = new DirectoryService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "TestAPIProject"
                });
                
                var request = service.Users.List();
                request.Customer = "test.example.com";
                request.Domain = "test.example.com";
                var result = await request.ExecuteAsync();
                
                
                Console.WriteLine(result);
                
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
            }
        }

The JSON token is correct for this, as far as I am aware. I believe that it is either the Customer or Domain that I am passing is the issue but I have tried out a lot of different options and still get the badRequest.

I am using a Google Workspace service account to send the request. Made sure to use that and not the OAuth token.

1

There are 1 answers

1
Linda Lawton - DaImTo On BEST ANSWER

To begin with you commented out CreateWithUser which is required for impersonation. after that i would check your Customer to be sure thats right.

using Google.Apis.Auth.OAuth2;
using Google.Apis.Admin.Directory.directory_v1;
using Google.Apis.Services;

Console.WriteLine("Hello, Google Calendar Workspace sample!");

var scopes = new[] { DirectoryService.Scope.AdminDirectoryUser };

const string workspaceAdmin = "[email protected]";

const string credentials = @"C:\Development\FreeLance\GoogleSamples\Credentials\workspaceserviceaccount.json";

var credential = GoogleCredential.FromFile(credentials).CreateScoped(scopes).CreateWithUser(workspaceAdmin);

var services = new DirectoryService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
});

var request = services.Users.List();
request.Customer = "my_customer";
request.MaxResults = 10;
request.OrderBy = UsersResource.ListRequest.OrderByEnum.Email;
    
var results = request.Execute();

var users = results.UsersValue;

if (users.Count == 0)
{
    Console.WriteLine("No Users");
    return;
}

Console.WriteLine("Users:");
foreach (var user in users)
{
    Console.WriteLine($"{user.PrimaryEmail} ({user.Name.FullName})");
}