在 C# .NET 中使用服务帐户而不是个人帐户进行身份验证以使用 Google Sheets [英] Authenticate to use Google Sheets with service account instead of personal account in C# .NET

查看:93
本文介绍了在 C# .NET 中使用服务帐户而不是个人帐户进行身份验证以使用 Google Sheets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个应用程序,它使用了一些 Google 表格.

I have an application that I developed that utilizes a few Google Sheets.

我知道如何使用以下代码访问 Google Sheets API:

I was able to figure out how to get it to have access to the Google Sheets API using the following code:

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

此应用程序将被其他一些人使用 - 但当他们第一次运行该应用程序时,它会要求他们登录 Google - 但他们的帐户并未授予他们适当的访问权限.

This application will be used by a few other people - but the first time they run the application it asks them to login to Google - but their accounts don't give them the appropriate access.

我认为(如果我错了,请纠正我)- 使用服务帐户应该可以解决我的问题,并且不再提示用户登录",但仍允许我的应用程序适当地读取/更新表格.

I think (correct me if I'm wrong) - using a Service Account should resolve my issue and no longer prompt a user to 'login', but still allow my application to read/update the Sheets appropriately.

我想使用我现有的代码并修改它以使用服务帐户,但我找不到关于如何执行此操作的任何好的文档.我已经创建了服务帐户并将 ServiceAccount.json 文件与当前的client_secret.json"文件放在同一位置,但我不确定如何进一步进行.

I'd like to take my existing code and modify it to use a Service Account but I can't find any good documentation on how to do that. I have created the Service Account and have the ServiceAccount.json file in the same spot as the current 'client_secret.json' file but am unsure how to proceed much further.

我尝试将代码更改为:

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

但它失败了 - 凭证变量给出了一个错误.

But it fails - the credential variable gives an error.

有什么想法吗?

推荐答案

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

You should have created the service account and stored the json credential file:

然后试试这个:

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

这篇关于在 C# .NET 中使用服务帐户而不是个人帐户进行身份验证以使用 Google Sheets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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