json 在C# .NET中使用服务帐户而不是个人帐户进行身份验证以使用Google表格

6ovsh4lw  于 2023-05-19  发布在  C#
关注(0)|答案(3)|浏览(247)

我有一个应用程序,我开发,利用了一些谷歌表。
我能够使用以下代码弄清楚如何让它访问Google Sheets API:

UserCredential credential;
    using (var stream =
                  new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
    {
        string credPath = System.Environment.GetFolderPath(
            System.Environment.SpecialFolder.Personal);

        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        Console.WriteLine("Credential file saved to: " + credPath);
    }
    // Create Google Sheets API service.
    var service = new SheetsService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });

这个应用程序将被其他一些人使用-但他们第一次运行应用程序时,它要求他们登录到谷歌-但他们的帐户不给予他们适当的访问权限。
我认为(如果我错了,请纠正我)-使用服务帐户应该解决我的问题,不再提示用户“登录”,但仍然允许我的应用程序阅读/更新工作表适当。
我想把我现有的代码,并修改它使用一个服务帐户,但我找不到任何好的文档如何做到这一点。我已经创建了服务帐户,并将ServiceAccount.json文件与当前的'client_secret.json'文件放在同一位置,但不确定如何进一步进行。
我尝试将代码改为:

ServiceAccountCredential credential;
    //UserCredential credential;
    using (var stream =
        new FileStream("HelperServiceAccount.json", FileMode.Open, FileAccess.Read))
    {
        string credPath = System.Environment.GetFolderPath(
            System.Environment.SpecialFolder.Personal);

        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
            )
        Console.WriteLine("Credential file saved to: " + credPath);
    }
    // Create Google Sheets API service.
    var service = new SheetsService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });

但它失败了-credential变量给出了一个错误。
有什么想法吗

m528fe3b

m528fe3b1#

您应该已经创建了服务帐户并存储了json凭据文件:
那么试试这个:

ServiceAccountCredential credential;
        string[] Scopes = { SheetsService.Scope.Spreadsheets };
        string serviceAccountEmail = "xxxxxxxxxxxx@xxxxxxxx.iam.gserviceaccount.com";
        string jsonfile = "xxxxxxxx-xxxxxxx.json";
        using (Stream stream = new FileStream(@jsonfile, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            credential = (ServiceAccountCredential)
                GoogleCredential.FromStream(stream).UnderlyingCredential;

            var initializer = new ServiceAccountCredential.Initializer(credential.Id)
            {
                User = serviceAccountEmail,
                Key = credential.Key,
                Scopes = Scopes
            };
            credential = new ServiceAccountCredential(initializer);
        }
hlswsv35

hlswsv352#

最短代码:

var credential = (ServiceAccountCredential)GoogleCredential
    .FromFile("client_secret.json")
    .CreateScoped(SheetsService.Scope.Spreadsheets)
    .UnderlyingCredential;

var service = new SheetsService(new BaseClientService.Initializer
{
    HttpClientInitializer = credential,
    ApplicationName = AppName,
});
xqk2d5yq

xqk2d5yq3#

我创建这个项目是为了允许用户使用json或p12凭据文件创建服务帐户凭据。如果您想从您的域访问用户数据,请确保在此之前启用广域委派选项。
GoogleApiServiceFactory

相关问题