Google has retired their older authentication API. OAuth 2.0 should be used instead.
I spent too much time to figure out how to use newer Auth API with older GData API grabbing bits and pieces of information here and there from the Internet.
I decided to share all the the details with screenshots to save your time.
-
Hit
Create Project
button
- Create project. Type in some name.
- Go to
API & Auth
>Credentials
and hitCreate new Client ID
button. It will create JSON key for you automatically – ignore that.
- Hit
Generate new P12 key
- File download will start automatically. Remember the password, you will need it to open the file you just downloaded.
- Rename downloaded file to Key.p12 and add it to your solution. Make sure you set
Build Action
andCopy to Output Directory
accordingly.
-
Install Google API Auth using Nuget. Type the following in the Package Manager Console
Install-Package Google.Apis.Auth
- Copy service account email address that was generated in Step #4.
-
Grant appropriate permission to this user in your Google Spreadsheet.
-
Use the following code to query the spreadsheet. Replace email and Google spreadsheet URL address in the code below.
const string ServiceAccountEmail = "452351479-q41ce1720qd9l94s8847mhc0toao1fed@developer.gserviceaccount.com"; var certificate = new X509Certificate2("Key.p12", "notasecret", X509KeyStorageFlags.Exportable); var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(ServiceAccountEmail) { Scopes = new[] { "https://spreadsheets.google.com/feeds" } }.FromCertificate(certificate); var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer); if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result) throw new InvalidOperationException("Access token request failed."); var requestFactory = new GDataRequestFactory(null); requestFactory.CustomHeaders.Add("Authorization: Bearer " + credential.Token.AccessToken); var service = new SpreadsheetsService(null) { RequestFactory = requestFactory }; var query = new ListQuery("https://spreadsheets.google.com/feeds/list/0ApZkobM61WIrdGRYshh345523VNsLWc/1/private/full"); var feed = service.Query(query); var rows = feed.Entries .Cast<ListEntry>() .Select(arg => new { Field0 = arg.Elements[0].Value, Field1 = arg.Elements[1].Value }) .ToList();