使用谷歌API目录从C#认证错误 [英] Authentication Error using Google Directory API from C#

查看:593
本文介绍了使用谷歌API目录从C#认证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打电话给谷歌Apps目录API,这样我可以列出用户在我的组织的谷歌应用服务帐户

我通过自己的文档搜罗几个小时,已经能够拿出低于code。不过,我得到了下面的错误。 凭据无效[401] 我怀疑它与我构建了ServiceAccountCredential的方式做

  [STAThread]
    静态无效的主要(字串[] args)
    {
        Console.WriteLine(谷歌目录服务API);
        Console.WriteLine(================================);
        尝试
        {
            新计划()的run()等待()。
        }
        赶上(AggregateException前)
        {
            的foreach(在ex.InnerExceptions变种E)
            {
                Console.WriteLine(错误:+ e.Message);
            }
        }
        Console.WriteLine(preSS任意键继续......);
        Console.ReadKey();
    }    私人异步任务的run()
    {
        使用(VAR流=新的FileStream(../../客户secrets.json,FileMode.Open,FileAccess.Read))
        使用(VAR读者=新的StreamReader(流))
        {
            JObject clientJObject = JObject.Parse(reader.ReadToEnd());            VAR秘密=新ClientSecrets
            {
                客户端Id = clientJObject.GetValue(的client_id)。toString()方法,
                ClientSecret = clientJObject.GetValue(PRIVATE_KEY)。的ToString()
            };            。VAR tokenUrl = clientJObject.GetValue(token_uri)的ToString();            VAR证书=新ServiceAccountCredential(新ServiceAccountCredential.Initializer(secrets.ClientId,tokenUrl).FromPrivateKey(secrets.ClientSecret));            VAR初始化=新BaseClientService.Initializer()
            {
                HttpClientInitializer =凭证,
                应用程序名称=我的目录列表应用程序,
            };            VAR的服务=新DirectoryService中(初始化);            VAR用户=等待service.Users.List()ExecuteAsync()。
            。users.UsersValue.ToList()的ForEach(U =>
            {
                Console.WriteLine(u.PrimaryEmail);
            });
        }
    }

我Secrets.Json文件是一个有点像如下。我删除了大部分私钥部分的

  {
  类型:service_account,
  PROJECT_ID:service.account,
  private_key_id:fd6f98b603dd5a065c87a8d34a4e428cf6277a35,
  PRIVATE_KEY:----- BEGIN PRIVATE KEY ----- \\ n ----- END PRIVATE KEY ----- \\ n
  client_email:service.account@appspot.gserviceaccount.com,
  CLIENT_ID:102588765356663060837,
  auth_uri:https://accounts.google.com/o/oauth2/auth,
  token_uri:https://accounts.google.com/o/oauth2/token,
  auth_provider_x509_cert_url:https://www.googleapis.com/oauth2/v1/certs,
  client_x509_cert_url:https://www.googleapis.com/robot/v1/metadata/x509/service.account%40appspot.gserviceaccount.com
}


解决方案

管理

第1步:登录到管理控制台

第二步:启用确保API访问安全和GT; API参考>启用API访问

步骤3:启用谷歌企业应用套件域范围内的代表团


  • 头以上的开发控制台

  • 选择API项目

  • 然后到凭证>管理服务帐户> 编辑服务帐户>启用谷歌企业应用套件域范围内的代表团

  • 返回> 查看客户端ID

  • 复制客户端ID,你会需要的

第四步:注册API客户端和示波器安全和GT;高级设置>管理API客户端访问

第五步:创建服务帐户私钥


  • 创建凭证>服务帐户钥匙> 选择服务帐户> P12对于使用P12格式code向后兼容性>关闭

  • 这将自动下载关键code到系统中。因为它是非常重要的保存此键

的code

首先,你需要安装以下软件包

 安装包Google.Apis.Admin.Directory.directory_v1
安装包Newtonsoft.Json

和最后code以下

 使用Google.Apis.Auth.OAuth2;
使用Google.Apis.Services;
使用系统;
使用System.Linq的;
使用Google.Apis.Admin.Directory.directory_v1;
使用System.Security.Cryptography.X509Certificates;命名空间GoogleApis
{    ///<总结>
    ///此示例演示了服务帐户的服务最简单的用例。
    ///证书需要从谷歌的开发者控制台下载
    ///<见CREF =htt​​ps://console.developers.google.com/>
    ///创建另一个客户端ID ... - > 服务帐户 - >下载证书,
    ///将其重命名为key.p12并将其添加到项目中。不要忘了更改构建行动
    ///到内容和复制到输出目录复制,如果新。
    ///< /总结>
    公共类节目
    {
        公共静态无效的主要(字串[] args)
        {
            //服务帐户的电子邮件
            //注意:这是服务客户的帐户
            字符串serviceAccountEmail =service.account@appspot.gserviceaccount.com;            //路径下载的密钥
            VAR路径= @路径\\要\\ key.p12            //生成使用从API控制台下载的密钥的证书
            VAR证书=新X509Certificate2(路径,notasecret,X509KeyStorageFlags.Exportable);            //创建凭据
            ServiceAccountCredential serviceCredential =新ServiceAccountCredential(
               新ServiceAccountCredential.Initializer(serviceAccountEmail)
               {
                   //定义作用域所需的凭据来访问
                   范围=新[]
                   {
                       DirectoryService.Scope.AdminDirectoryUser,
                   },
                   //指定此服务认证是模拟用户。通常情况下你谷歌Apps管理员帐户
                   用户=admin@domain.com
               } .FromCertificate(证书));            //实例化服务(可以是任何的谷歌API服务的)
            VAR的服务=新DirectoryService中(新BaseClientService.Initializer()
            {
                HttpClientInitializer = serviceCredential,
            });            //定义的请求参数。
            UsersResource.ListRequest请求= service.Users.List();
            //设置请求的域名
            request.Domain =domain.com            //列表的用户。
            VAR用户= request.Execute()UsersValue。
            users.Select(U => u.PrimaryEmail).ToList()的ForEach(Console.WriteLine)。
            Console.ReadKey();
        }
    }
}

I'm trying to call the Google Apps Directory API so that I can list users to my organization's Google Apps Account

I have scoured for hours through their documentation and have been able to come up with the code below. However, I get the following error. Invalid Credentials [401] I suspect that it has to do with the way I constructed the ServiceAccountCredential

    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("Google Directory Service API");
        Console.WriteLine("================================");
        try
        {
            new Program().Run().Wait();
        }
        catch (AggregateException ex)
        {
            foreach (var e in ex.InnerExceptions)
            {
                Console.WriteLine("ERROR: " + e.Message);
            }
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

    private async Task Run()
    {
        using (var stream = new FileStream("../../client-secrets.json", FileMode.Open, FileAccess.Read))
        using (var reader = new StreamReader(stream))
        {
            JObject clientJObject = JObject.Parse(reader.ReadToEnd());

            var secrets = new ClientSecrets
            {
                ClientId = clientJObject.GetValue("client_id").ToString(),
                ClientSecret = clientJObject.GetValue("private_key").ToString()
            };

            var tokenUrl = clientJObject.GetValue("token_uri").ToString();

            var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(secrets.ClientId, tokenUrl).FromPrivateKey(secrets.ClientSecret));

            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "My Directory Listing App",
            };

            var service = new DirectoryService(initializer);

            var users = await service.Users.List().ExecuteAsync();
            users.UsersValue.ToList().ForEach(u =>
            {
                Console.WriteLine(u.PrimaryEmail);
            });
        }
    }

My Secrets.Json file is a bit like follows. I removed the majority of the private key part

{
  "type": "service_account",
  "project_id": "service.account",
  "private_key_id": "fd6f98b603dd5a065c87a8d34a4e428cf6277a35",
  "private_key": "-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\n",
  "client_email": "service.account@appspot.gserviceaccount.com",
  "client_id": "102588765356663060837",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service.account%40appspot.gserviceaccount.com"
}

解决方案

Administration

Step 1: Login to the Admin console

Step 2: Ensure API Access is enabled Security > Api Reference > Enable API Access

Step 3: Enable Google Apps Domain-wide Delegation

  • Head over to the Dev Console
  • Select the API Project
  • Then go to Credentials > Manage Service Accounts > "Edit Service Account" > Enable Google Apps Domain-wide Delegation
  • "Go Back" > "View ClientID"
  • Copy the Client ID as you'll be needing that

Step 4: Register API Client and Scopes Security > Advanced Settings > Manage API client access

Step 5: Create Service Account Private Key

  • Create Credentials > Service Account Key > "Select Service Account" > P12 "For backward compatibility with code using the P12 format" > Close
  • This will automatically download the Key code to your system. Save this key as it is very important

The Code

First you need to install the following packages

install-package Google.Apis.Admin.Directory.directory_v1
install-package Newtonsoft.Json

And finally the code below

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
using System.Linq;
using Google.Apis.Admin.Directory.directory_v1;
using System.Security.Cryptography.X509Certificates;

namespace GoogleApis
{

    /// <summary>
    /// This sample demonstrates the simplest use case for a Service Account service.
    /// The certificate needs to be downloaded from the Google Developers Console
    /// <see cref="https://console.developers.google.com/">
    ///   "Create another client ID..." -> "Service Account" -> Download the certificate,
    ///   rename it as "key.p12" and add it to the project. Don't forget to change the Build action
    ///   to "Content" and the Copy to Output Directory to "Copy if newer".
    /// </summary>
    public class Program
    {
        public static void Main(string[] args)
        {
            //Service account Email 
            //NOTE: This is the account for the Service Client
            string serviceAccountEmail = "service.account@appspot.gserviceaccount.com";

            //Path to Downloaded Key
            var path = @"Path\To\key.p12";

            //Generate a Certificate using the Key downloaded from the Api Console
            var certificate = new X509Certificate2(path, "notasecret", X509KeyStorageFlags.Exportable);

            //Create the Credential
            ServiceAccountCredential serviceCredential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(serviceAccountEmail)
               {
                   //Define the Scopes You want the credential to Access
                   Scopes = new[]
                   {
                       DirectoryService.Scope.AdminDirectoryUser,
                   },
                   //Specify the User that this service Credential is Impersonating. Typically your Google Apps Admin Account
                   User = "admin@domain.com"
               }.FromCertificate(certificate));

            //Instantiate the Service (Could be any of the Google Api Services)
            var service = new DirectoryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = serviceCredential,
            });

            // Define parameters of request.
            UsersResource.ListRequest request = service.Users.List();
            //Set the Domain of the Request
            request.Domain = "domain.com";

            // List users.
            var users = request.Execute().UsersValue;
            users.Select(u => u.PrimaryEmail).ToList().ForEach(Console.WriteLine);
            Console.ReadKey();
        }
    }
}

这篇关于使用谷歌API目录从C#认证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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