[英]AdminSettings API using service account in a C# Console application
我正在尝试通过服务帐户使用Google管理员设置API ,但C#控制台应用程序未成功。
据我了解,我首先必须获得一个OAuth令牌。 我已经成功尝试了两种方法:使用Google.Apis.Auth.OAuth2.ServiceAccountCredentials或通过手动创建JWT断言。
但是,当我使用OAuth令牌(例如maximumNumberOfUsers)调用Admin Settings API时,总是收到403错误,显示“您无权对域xxx执行操作”消息。
我下载了GAM,因为作者也调用了此API,因此我可以编写相同的HTTP请求。 就像GAM Wiki中解释的那样,我按照所有步骤创建了一个新的服务帐户和一个新的OAuth客户端ID,以便可以确定这不是范围问题。 我也在该线程中激活了Jay Lee提议的调试模式。 就像线程注释中所述,它仍然无法与我的OAuth令牌一起使用,但对API的调用会通过GAM OAuth令牌成功进行。
因此,它似乎与OAuth令牌本身有关。 创建OAuth令牌时遇到的问题是,我无法指定“ sub”属性(或ServiceAccountCredentials的用户)。 如果添加它,则会收到“禁止的请求的客户端未经授权”的403禁止响应。 在生成令牌时(即在调用API之前)作为error_description。 因此,也许是问题所在,但是当我使用管理员电子邮件时,我看不到如何解决它。
另一种可能性是该API需要OAuth客户端凭据,因为GAM需要2种不同类型的凭据,即服务帐户和OAuth客户端。 由于我只能在我的项目中使用服务帐户凭据,因此我担心这种情况会卡住...
我看不到其他选择,并且我都坚持使用,因此对您的帮助表示赞赏。 谢谢!
我的代码:
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/ '也是必要的,但我已经将其添加到允许范围的列表中。 谢谢周杰伦!
编辑2:我还更新了源代码,以便将来提供帮助。
您需要授予服务帐户的客户ID访问管理员设置API范围的权限。 请遵循Drive域范围的委托说明,但正确范围内的sub除外。 然后,您可以设置sub =且没有错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.