Google directory API to get list of users in my domain in C#

267 Views Asked by At

I am trying to use Google directory API in .NET Console Application where I want to get a user information. I keep receiving not authorised error, even though I have added the scope, done the domain wide delegation etc. Please help! What am I missing here?

enter image description here

static void Main(string[] args)
        {
            
            //Service account Email 
            //NOTE: This is the account for the Service Client   
            string serviceAccountEmail = "[email protected]";

            //Path to Downloaded Key
            var path = @"D:\Anusha\directory-read.p12";
            if (!File.Exists(path))
            {
                return;
            }

            var certificate = new X509Certificate2(path, "notasecret", X509KeyStorageFlags.Exportable);

            ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { DirectoryService.Scope.AdminDirectoryUserReadonly, DirectoryService.Scope.AdminDirectoryUser }
            }.FromCertificate(certificate));

            var service = new DirectoryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Directory API Sample"
            });

            UsersResource.GetRequest request = service.Users.Get("[email protected]");
            request.Execute();
}
1

There are 1 best solutions below

0
Linda Lawton - DaImTo On

The issue is that you are using a service account. A service account does not have direct access to directory admin until you configure domain wide delegation.

You also need to denote the user who you wish to impersonate.

var gsuiteUser = "[email protected]";

        var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccount)
        {
            User = gsuiteUser,
            Scopes = new[] { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels }

        }.FromCertificate(certificate);