How to login to Google API with Service Account in C# - Invalid Credentials

后端 未结 5 2347
孤独总比滥情好
孤独总比滥情好 2021-02-02 08:58

I\'m beating myself bloody trying to get a simple service acccount login to work in C#, to Google API and Google Analytics. My company is already getting data into Analytics, an

5条回答
  •  暖寄归人
    2021-02-02 09:48

    In 2020 you don't need to do all this and the GoogleCredential works fine. The code in the question looks correct except for one line:

    credentials.CreateScoped(new string[] { DriveService.Scope.Drive });
    

    The CreateScoped method returns a copy of the credentials. If you reassign it back to itself it just works.

    For the sake of completeness, this is my test code that works perfectly:

    using (var stream =
                new FileStream("drive-credentials.json", FileMode.Open, FileAccess.Read))
            {                
                var credentials = GoogleCredential.FromStream(stream);
                if (credentials.IsCreateScopedRequired)
                {
                    credentials = credentials.CreateScoped(new string[] { DriveService.Scope.Drive });
                }
    
    
                var service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credentials,
                    ApplicationName = "application name",                    
                });
    
                FilesResource.ListRequest listRequest = service.Files.List();
                listRequest.PageSize = 10;
                listRequest.Fields = "nextPageToken, files(id, name)";
    
                // List files.
                IList files = listRequest.Execute()
                    .Files;
            }
    

提交回复
热议问题