Google APIs Client Library for C++ | A C++ library for client applications to access Google APIs. |
This document discusses authenticating and authorizing requests when using the Google APIs Client Library for C++. It provides a high level overview of the components involved and some basic use cases.
Authentication refers to the ability for the client to prove that it is acting on behalf of a particular user. The document Using OAuth 2.0 for Login may provide useful supplemental information on authenticating with OAuth 2.0.
Authorization refers to the ability for an authenticated user to give permission for an application they are using to access certain data that is private to them. OAuth 2.0 permits services to pick the degree of granularity that their data can be protected with so as to provide some levels of access to an application without providing complete access. The document Using OAuth 2.0 to Access Google APIs may provide useful supplemental material to understand how to use OAuth 2.0 for authorization works in general.
Contents
Typical use case examples
These examples show how to use the core OAuth 2.0 components to make authorized calls into cloud APIs. The following snippet applies to all the examples in this section.
#include "googleapis/client/auth/file_credential_store.h" #include "googleapis/client/auth/oauth2_authorization.h" #include "googleapis/client/transport/http_authorization.h" using googleapis_client::CredentialStore; using googleapis_client::FileCredentialStoreFactory; using googleapis_client::OAuth2AuthorizationFlow; using googleapis_client::OAuth2Credential; using googleapis_client::OAuth2RequestOptions;
Creating and configuring an OAuth2AuthorizationFlow
Typically flows are created from client secrets files. The Preparing to use the SDK section of the Getting Started document discusses how to obtain a client_secrets file. The Google APIs Console Help may also be of use for more information on creating a client secrets file.
The following snippet:
- Loads a flow definition from a client-secrets file.
- Sets the default OAuth 2.0 scope when asking for credentials.
- Individual requests can override this later.
- Sets a callback for obtaining Authorization Codes.
- This is used to obtain first-time authorization.
- Binds a credential store to remember and recall authorizations.
- See
FileCredentialStoreFactory
in oauth2_authorization.h. - Credentials will be stored in files named
CalendarSample
.
- See
// We're passing in NULL here assuming that you have set // HttpTransport::default_transport_factory. Otherwise instead pass // a transport, such as CurlHttpTransportFactory::New(). flow_.reset( OAuth2AuthorizationFlow::MakeFlowFromClientSecretsPath( client_secrets_path, transport, &status)); CHECK(status.ok()) << status.error_message(); util::Status store_status; string dir; store_status = FileCredentialStoreFactory::GetSystemHomeDirectoryStorePath(&dir); if (store_status.ok()) { FileCredentialStoreFactory store_factory(dir); flow_->ResetCredentialStore( store_factory.NewCredentialStore("CalendarSample", &store_status)); } if (!store_status.ok()) { LOG(WARNING) << "Not adding a credential store: " << store_status.error_message(); } flow_->set_default_scopes(CalendarService::SCOPES::CALENDAR); flow_->mutable_client_spec()->set_redirect_uri( OAuth2AuthorizationFlow::kOutOfBandUrl); flow_->set_authorization_code_callback( NewPermanentCallback(&PromptShellForAuthorizationCode, flow_.get()));
Obtaining and refreshing credentials
The following snippet refreshes a credential for the given user.
- If there is a credential store on the flow, it will be consulted.
- If there is no store or the user has no store credentials then
the flow's AuthorizationCodeCallback will be called and the returned
code turned into an access token (and refresh token).
- The newly obtained credential will be written into the store, if a store is bound to the flow.
- The refresh will fail if there is no AuthorizationCodeCallback or the authorization code could not be turned into an access token.
util::Status RefreshCredentialForUser( const string& id, OAuth2Credential* credential) { OAuth2RequestOptions options; options.user_id = id; return flow_->RefreshCredentialWithOptions(options, credential); }
Core components
The OAuth 2.0 module builds on abstract authorization concepts introduced in the HTTP Transport Layer and makes them specific to using OAuth2. The design goals were more to avoid a dependency on OAuth 2.0 in the implementation of the transport layer than to permit other authorization schemes.
OAuth2Credential
An OAuth2Credential
is an object that contains the
credential data for a specific user. This includes both the short-lived
access token as well as the permanent refresh token that can be used
to obtain new access tokens. The credential object also knows how to
authorize requests by adding the OAuth 2.0 authorization header with the
access token. Credentials are bound to HttpRequests
so that
they can authorize requests when they are executed.
CredentialStore
A CredentialStore
provides persistent storage to credentials.
Although the access tokens in the credentials have a limited lifespan,
the refresh tokens are valid indefinitely until they are explicitly
revoked. Storing a credential in a store for later retrieval will allow
a new access token to be granted for an existing refresh token. Otherwise
you will need to ask the user to authorize access over and over again
each time they use the application.
FileCredentialStore
- Implements a credential store that writes to files.
The default configuration uses plain-text files secured by the
operating system. These can be made more secure by adding
an encryption/decryption
Codec
.
See the Credential Store document for more
information about using CredentialStore
or adding your
own mechanism.
OAuth2TokenRequest
An OAuth2TokenRequest
is a request made to an OAuth 2.0 server.
Internally it is implemented in terms of HttpRequest
for
the communication. There are specific derived classes for the different
types of requests made to protocols. Most client applications will issue
requests indirectly using an OAuth2AuthorizationFlow
rather than use explicit token requests.
OAuth2RevokeTokenRequest
- Revokes the access token and refresh token so that they are no longer valid. The user will have to re-authorize future access.
OAuth2ExchangeAuthorizationCodeRequest
- Exchanges an authentication code for an access token and refresh token. Authorization codes are only good one time so this request can only be sent once.
OAuth2RefreshTokenRequest
- Obtains a new access token from an existing refresh token.
OAuth2AuthorizationFlow
An OAuth2AuthorizationFlow
is a high level object that
implements an OAuth 2.0 workflow and interactions with an OAuth 2.0 server.
The flow has factory methods to create OAuth2TokenRequests
as well has methods to orchestrate the entire workflow as needed to
obtain a credential.
The flow can accept a callback to obtain the OAuth 2.0 Authorization Code to obtain the initial access token and refresh token from. This step requires specific application integration to authenticate the user and prompt them to grant authorization.
If a flow has a CredentialStore
bound to it then it will
automatically use that store as a cache.
OAuth2InstalledApplicationFlow
- Implements the OAuth 2.0 for Installed Applications use case.
OAuth2WebApplicationFlow
- Implements the
OAuth 2.0 for Web Server Applications use case.
Adds
offline_access_type
andforce_approval_prompt
parameters.