Qadmium Qadmium - 3 months ago 113
C# Question

How to authenticate in Google Spreadsheet Api V4 with Server Key

I'm trying to use google spreadsheets with server key (created in console.cloud.google.com) like this

var service = new SheetsService(new BaseClientService.Initializer
{
ApplicationName = "myappname",
ApiKey = "mykey"
});


But after first request i'm receiving an error

Message[The request does not have valid authentication credentials.]


So how to authenticate using only server key?

May be it's better to use service account credentials to work with api from server (if it's possible of course)?

Answer

Try this code written by Владимир Рак:

var certificate = new X509Certificate2("pathTo***.p12", "notasecret", X509KeyStorageFlags.Exportable);
        var serviceAccountEmail = "********-*********@developer.gserviceaccount.com";
        var userAccountEmail = "******@gmail.com";
        ServiceAccountCredential credential = new ServiceAccountCredential(
                   new ServiceAccountCredential.Initializer(serviceAccountEmail)
                   {
                       Scopes = new[] { DriveService.Scope.Drive },
                       User = userAccountEmail

}.FromCertificate(certificate)); // Create the service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "*****", });

Comments