AdminSettings API using service account in a C# Console application
Asked Answered
P

1

0

I'm trying to use the Google Admin Settings API with a Service Account with no success from a C# Console application.

From what I've understood, I first have to get an OAuth token. I've tried 2 methods successfully for this: using Google.Apis.Auth.OAuth2.ServiceAccountCredentials or by creating manually the JWT assertion.

But when I call an Admin Settings API with the OAuth token (maximumNumberOfUsers for instance), I always get a 403 error with " You are not authorized to perform operations on the domain xxx" message.

I downloaded GAM as the author calls this API too so that I can compose the same HTTP requests. Like explained in GAM wiki, I followed all the steps to create a new Service Account and a new OAuth Client ID so that I can be sure it's not a scope issue. I also activated the debug mode like proposed by Jay Lee in this thread. Like explained in the thread comments, it still doesn't work with my OAuth token but the call to the API succeeds with GAM OAuth token.

So it seems it's related to the OAuth token itself. An issue I get while creating the OAuth token is that I can't specify the "sub" property (or User for ServiceAccountCredentials). If I add it, I get a 403 Forbidden response with "Requested client not authorized." as error_description while generating the token i.e. before calling the API. So maybe it is the issue but I don't see how to fix it as I use an Admin email.

Another possibility is that this API needs the OAuth Client credentials as GAM requires 2 different types of credentials, Service Account and OAuth Client. As I only can use Service Account credentials in my project, I'm afraid I will be stuck if it is the case...

I don't see other options and I'm stuck with both, so any help appreciated. Thanks!

My code:

public static string GetEnterpriseUsersCount()
{
    string domain = MYDOMAIN;

    string certPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
    certPath = certPath.Substring(0, certPath.LastIndexOf("\\") + 1) + "GAMCreds.p12";

    var certData = File.ReadAllBytes(certPath);
    X509Certificate2 privateCertificate = new X509Certificate2(certData, "notasecret", X509KeyStorageFlags.Exportable);

    ServiceAccountCredential credential = new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
        {
            Scopes = new[] { "https://apps-apis.google.com/a/feeds/domain/" },
            User = ADMIN_EMAIL
        }.FromCertificate(privateCertificate));

    Task<bool> oAuthRequest = credential.RequestAccessTokenAsync(new CancellationToken());
    oAuthRequest.Wait();


    string uri = string.Format("https://apps-apis.google.com/a/feeds/domain/2.0/{0}/general/maximumNumberOfUsers", domain);

    HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
    if (request != null)
    {
        request.Method = "GET";
        request.Headers.Add("Authorization", string.Format("Bearer {0}", credential.Token.AccessToken));

        // Return the response
        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                return sr.ReadToEnd();
            }
        }
    }

    return null;
}

Edit: I focused on scopes like advised by Jay Lee below and it appears that the missing scope was 'https://www.googleapis.com/auth/admin.directory.domain'. However, nowhere is this written in Admin Settings API documentation page. At least, I didn't find it. 'https://apps-apis.google.com/a/feeds/domain/' is necessary too but I already added it to the list of allowed scopes. Thanks Jay!

Edit 2: I also updated the source code so that it can help in the future.

Puffery answered 7/3, 2016 at 16:12 Comment(0)
B
1

You need to grant your service account's client ID access to the scopes for admins settings API. Follow the Drive domain wide delegation instructions except sub in the correct correct scope. Then you can set sub= without an error.

Buddhism answered 7/3, 2016 at 20:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.