Google Calendar API V3 - Authenticate with Hardcoded Credentials

Google Calendar API v3 - authenticate with hardcoded credentials

You will need to use both the Developer Key (API Key) and OAuth2. The developer key authenticates who wrote the software and is used for things like quota which is on a per developer basis not a per user basis. OAuth2 is for user authentication and will be need to access the non-public calendar.

OAuth2 has a renew token from which you can generate a session token and this means that you will not need to screen scrape the OAuth screens to get authenticated. To get this I would write a little command line application, or you use a one off PHP page.

  1. Under the Google Api Console go to API Access
  2. Generate a new Client ID and choose Installed Application ( as you will be authenticating you server as you not as your user)
  3. Either using a console app or a one off PHP page authenticate using OAuth and your google account (the one with the calendar you want access to)
  4. In the return from the authentication there should be a renew token, (called renew or refresh or something similar). Save this string and make it available to your PHP site.
  5. When you need to access the service your OAuth library should have a renew/refresh call. There is an example using .Net below.

private IAuthorizationState CreateAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { AdsenseService.Scopes.AdsenseReadonly.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
if (refreshToken.IsNotNullOrEmpty()) // refreshToken you stored in step 4
{
try
{
state.RefreshToken = refreshToken;
if (arg.RefreshToken(state)) // This is calling out to the OAuth servers with the refresh token getting back a session token, returns true if successful.
{
if (state.RefreshToken != refreshToken) // if the refresh token has changed, save it.
{
PersistRefreshToken(authorization.RefreshToken);
}
return this.authorization = state; // Retain the authorization state, this is what will authenticate your calls.
}
}
catch (ProtocolException ex) {...}

The AuthorisationState that has now been renewed can then be used to authenticate call you make to the API. this state can be used many time until it expires and then can be refreshed. As you are authenticating your application as yourself not as a user this AuthorisationState can be shared by all you sessions. Both the current AuthorisationState and the refresh token should be kept securely on your server and never sent to the client, if you ever sent these as part of a response your clients would have the same privileges as your code application

How do I authenticate Google Calendar API v3 without user interaction?

I don't know about using it in Delphi but there is a client API library for java, python... I've already used the java one and it's clearly explained how to use it in the documentation.

Google Calendar API 3 Doc page:
https://developers.google.com/google-apps/calendar/

However, the service asks you to be authentified to used it (which is your problem if I understand it well, you don't want the user to have to authenticate). So I suggest you to have a look on OAuth2.0. https://developers.google.com/google-apps/calendar/auth

Here are some simple of using google-api-java-client for exemple : https://code.google.com/p/google-api-java-client/wiki/OAuth2

And you should look more precisely at Google OAuth service account possibilities.
Service Account with OAuth2.0. (See here : https://developers.google.com/accounts/docs/OAuth2#serviceaccount).
It will provide a service account for your application, from which you will be able to handle calendars for your app.

And here you will find a sample showing how to do it with Java. (https://code.google.com/p/google-api-java-client/wiki/OAuth2#Service_Accounts). But maybe this is the public API Key you are talking about... Not sure I remember properly.

I hope this will help you to figure out how to do it.

Google Calendar V3 2 Legged authentication fails

NB: At the time of writing you can only used 2-legged authentication with Google Apps for Business/Eduction, this won't work on personal accounts as there's no way to get an OAuth 1.0 key/secret pair, you will have to use online authentication at least once (but you can use the out-of-browser option so you don't have to create a dedicated page).

Your code is correct apart from you don't need the first three lines relating to the NativeApplicationClient. This is most likely failing because you haven't properly set the OAuth keys, this causes 401s.

The other thing that causes 401s is using "matt@example.com" instead of "matt" as the username, the username is without including your domain.

To setup OAuth follow the instructions in this article from Google.

The most important parts to note are "Allow access to all APIs" must be unchecked and you have to individually grant access to all the APIs. If this hasn't been done you will get a 401 Invalid Credentials error. You then also need to turn those services on in the api console. If the api console step hasn't been done you will get a different error of 403 Daily Limit Exceeded.

This will cause you problems if you were previously relying on the "Allow access to all APIs" to use various services, you will have to grant them all individually as far as I understand it to use the v3 APIs. This seems to have been confirmed by google (4th reply by Nicolas Garnier) and is supposedly a bug, but that is an old post so it looks as if it's here to stay.

For reference once this has been done, this code will work, which in essence is the same as yours:

var auth = new OAuth2LeggedAuthenticator(domainName, consumerSecret, usernameWithoutDomain, domainName);  //domainName is presently used as the OAuth ConsumerKey for Google's 2legged OAuth

var service = new CalendarService(auth);

service.Key = serviceKey;

var results = service.CalendarList.List().Fetch();

Console.WriteLine(results.Items.Count);

So in summary:

In Google Apps "Manage this Domain" > "Advanced Tools"

Using "Manage OAuth domain key" enable key, generate secret, uncheck "Allow access to all APIs".

Using "Manage third party OAuth Client access" enable the APIs you want access to using your domain as "Client Name" and the APIs you want to access e.g. "http://www.google.com/calendar/feeds/" for the calendar.

Then finally create a project in the API console, use the APIKey as the serviceKey in the above example and turn on the APIs you need to access.

I am answering this as I kept hitting this question when I was trying to find out why my code was constantly returning 401s. Hope this helps someone as the Google instructions are awful and scattered all over the place at the moment.

How to list Google Calendar Events without User Authentication

What you need to do is use a Service account for this. You will then be able add the service accounts email address as a user to the calendar for your website. The Service account will then be able to access this calendar including the events

Google API : Unattended reading of calendar. How to login?

The first thing you need to do is obtain an access token. This will require a human.
Assuming you're using the Google APIs PHP Client, it can be done with this script (run from the command line).

NOTE: The snippet below works with a Client ID for Installed Applications. Make sure you create a client ID of this type in the Google API Access console.

require_once '../../src/apiClient.php';
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));

$client = new apiClient();
// Visit https://code.google.com/apis/console to create your client id and cient secret
$client->setClientId('INSERT_CLIENT_ID');
$client->setClientSecret('INSERT_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array(
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly',
));

$authUrl = $client->createAuthUrl();

print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

$_GET['code'] = $authCode;
$token = $client->authenticate();
var_dump($token);

This will give you a json encoded string containing your accessToken and refreshToken. The accessToken expires after 1 hour, but don't worry. The refreshToken will not expire (unless you uninstall the application), and can be used to obtain a new refreshToken. The client library takes care of this part.

Next, save the full json string token (not only the access_token property in a safe place and make sure it can't be read by others. Your app can then call $client->setAccessToken($token) where $token was looked up from the safe location (Again, $token is the full json-encoded string, not limited to its access_token property).

Now, you can make authenticated request to the Calendar APIs!

require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiCalendarService.php';
session_start();

$client = new apiClient();
$client->setApplicationName("Google Calendar PHP Sample Application");
$cal = new apiCalendarService($client);

$client->setAccessToken($tokenFromSafePlace);

$calList = $cal->calendarList->listCalendarList();
print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";


Related Topics



Leave a reply



Submit