在C#控制台应用程序中使用服务帐户的AdminSettings API [英] AdminSettings API using service account in a C# Console application

查看:81
本文介绍了在C#控制台应用程序中使用服务帐户的AdminSettings API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Google管理员设置API 使用服务帐户,但C#控制台应用程序中没有成功.

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

据我了解,我首先必须获得一个OAuth令牌.我已经成功尝试了两种方法:使用Google.Apis.Auth.OAuth2.ServiceAccountCredentials或通过手动创建JWT断言.

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.

但是,当我使用OAuth令牌(例如maximumNumberOfUsers)调用Admin Settings API时,总是会收到403错误,提示您无权对域xxx执行操作".

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.

我下载了 GAM ,因为作者也调用了此API,因此我可以编写相同的HTTP请求.如GAM Wiki中所述,我按照所有步骤创建了一个新的服务帐户和一个新的OAuth客户端ID,这样我就可以确定这不是范围问题.我还激活了Jay Lee 在此线程中提出的调试模式一个>.就像线程注释中所解释的那样,它仍然不能与我的OAuth令牌一起使用,但是对API的调用会通过GAM OAuth令牌成功进行.

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.

因此,它似乎与OAuth令牌本身有关.创建OAuth令牌时遇到的问题是我无法指定"sub"属性(或ServiceAccountCredentials的用户).如果添加它,则会收到禁止的请求的客户端未授权"的403禁止响应.在生成令牌时(即在调用API之前)作为error_description.因此,也许是问题所在,但是当我使用管理员电子邮件时,我看不到如何解决此问题.

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.

另一种可能性是该API需要OAuth客户端凭据,因为GAM需要两种不同类型的凭据,即服务帐户和OAuth客户端.由于我只能在我的项目中使用服务帐户凭据,因此,如果这样的话,我会被卡住...

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!

我的代码:

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;
}

编辑:我专注于以下Jay Lee建议的范围,似乎缺少的范围是' https://www.googleapis.com/auth/admin.directory.domain ".但是,在管理设置API"文档页面上没有任何内容.至少我没有找到它. ' https://apps-apis.google.com/a/feeds/domain/'也是必要的,但我已经将其添加到允许范围的列表中.谢谢杰伊!

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.

推荐答案

您需要授予服务帐户的客户ID访问管理员设置API范围的权限.遵循驱动器域范围内的授权说明,但正确范围内的子目录除外.然后,您可以设置sub =且没有错误.

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.

这篇关于在C#控制台应用程序中使用服务帐户的AdminSettings API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆