Using OAuth 2.0 for Web Server Applications

This document explains how web server applications use Google API Client Libraries or Google OAuth 2.0 endpoints to implement OAuth 2.0 authorization to access Google APIs. OAuth 2.0 allows users to share specific data with an application while keeping their usernames, passwords, and other information private. For example, an application can use OAuth 2.0 to obtain permission to upload videos to a user's YouTube channel.

This OAuth 2.0 flow is specifically for user authorization. It is designed for applications that can store confidential information and maintain state. A properly authorized web server application can access an API while the user interacts with the application or after the user has left the application.

Web server applications frequently also use service accounts to authorize API requests, particularly when calling Cloud APIs to access project-based data rather than user-specific data. Web server applications can use service accounts in conjunction with user authorization. Note that the YouTube Data API supports the service account flow only for YouTube content owners that own and manage multiple YouTube channels. Specifically, content owners can use service accounts to call API methods that support the onBehalfOfContentOwner request parameter.

Client libraries

The language-specific examples on this page use Google API Client Libraries to implement OAuth 2.0 authorization. To run the code samples, you must first install the client library for your language.

When you use a Google API Client Library to handle your application's OAuth 2.0 flow, the client library performs many actions that the application would otherwise need to handle on its own. For example, it determines when the application can use or refresh stored access tokens as well as when the application must reacquire consent. The client library also generates correct redirect URLs and helps to implement redirect handlers that exchange authorization codes for access tokens.

Client libraries are available for the following languages:

Prerequisites

Enable APIs for your project

Any application that calls Google APIs needs to enable those APIs in the API Console. To enable APIs for your project:

  1. Open the Library page in the API Console.
  2. Select the project associated with your application. Create a project if you do not have one already.
  3. Use the Library page to find and enable the YouTube Data API. Find any other APIs that your application will use and enable those, too.

Create authorization credentials

Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server. The following steps explain how to create credentials for your project. Your applications can then use the credentials to access APIs that you have enabled for that project.

  1. Open the Credentials page in the API Console.
  2. Click Create credentials > OAuth client ID.
  3. Complete the form. Set the application type to Web application. Applications that use languages and frameworks like PHP, Java, Python, Ruby, and .NET must specify authorized redirect URIs. The redirect URIs are the endpoints to which the OAuth 2.0 server can send responses. For testing, you can specify URIs that refer to the local machine, such as http://localhost:8080.

    We recommend that you design your app's auth endpoints so that your application does not expose authorization codes to other resources on the page.

After creating your credentials, download the client_secrets.json file and securely store it in a location that only your application can access.

Identify access scopes

Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there may be an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.

Before you start implementing OAuth 2.0 authorization, we recommend that you identify the scopes that your app will need permission to access.

We recommend that your application request access to authorization scopes via an incremental authorization process, in which your application requests access to user data in context. This best practice helps users to more easily understand why your application needs the access it is requesting.

The YouTube Data API uses the following scopes:

Scopes
https://www.googleapis.com/auth/youtubeManage your YouTube account
https://www.googleapis.com/auth/youtube.force-sslManage your YouTube account
https://www.googleapis.com/auth/youtube.readonlyView your YouTube account
https://www.googleapis.com/auth/youtube.uploadManage your YouTube videos
https://www.googleapis.com/auth/youtubepartnerView and manage your assets and associated content on YouTube
https://www.googleapis.com/auth/youtubepartner-channel-auditView private information of your YouTube channel relevant during the audit process with a YouTube partner

The OAuth 2.0 API Scopes document contains a full list of scopes that you might use to access Google APIs.

Obtaining OAuth 2.0 access tokens

The following steps show how your application interacts with Google's OAuth 2.0 server to obtain a user's consent to perform an API request on the user's behalf. Your application must have that consent before it can execute a Google API request that requires user authorization.

Step 1: Configure the client object

If you are using a Google API client library to handle the OAuth 2.0 flow, your first step is to configure the client object. Your application uses the client object to obtain user authorization and to make authorized API requests.

The client object identifies the scopes that your application is requesting permission to access. These values inform the consent screen that Google displays to the user. The Choosing access scopes section provides information about how to determine which scopes your application should request permission to access.

The tabs below show examples of how to do this. All of the examples use incremental authorization to request access to user data in context.

PHP

Use the client_secrets.json file that you created to configure a client object in your application. When you configure a client object, you specify the scopes your application needs to access, along with the URL to your application's auth endpoint, which will handle the response from the OAuth 2.0 server.

For example, to request offline access to manage a user's YouTube account:

$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setAccessType("offline");        // offline access
$client->setIncludeGrantedScopes(true);   // incremental auth
$client->addScope(GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');

Your application uses the client object to perform OAuth 2.0 operations, such as generating authorization request URLs and applying access tokens to HTTP requests.

Python

Use the client_secrets.json file that you created to configure a client object in your application. When you configure a client object, you specify the scopes your application needs to access, along with the URL to your application's auth endpoint, which will handle the response from the OAuth 2.0 server.

For example, to request offline access to manage a user's YouTube account:

from oauth2client import client

flow = client.flow_from_clientsecrets(
    'client_secrets.json',
    scope='https://www.googleapis.com/auth/youtube.force-ssl',
    redirect_uri='http://www.example.com/oauth2callback')
flow.params['access_type'] = 'offline'         # offline access
flow.params['include_granted_scopes'] = True   # incremental auth

Your application uses the client object to perform OAuth 2.0 operations, such as generating authorization request URLs and applying access tokens to HTTP requests.

Ruby

Use the client_secrets.json file that you created to configure a client object in your application. When you configure a client object, you specify the scopes your application needs to access, along with the URL to your application's auth endpoint, which will handle the response from the OAuth 2.0 server.

For example, to request offline access to manage a user's YouTube account:

require 'google/apis/youtube_v3'
require 'google/api_client/client_secrets'

client_secrets = Google::APIClient::ClientSecrets.load
auth_client = client_secrets.to_authorization
auth_client.update!(
  :scope => 'https://www.googleapis.com/auth/youtube.force-ssl',
  :redirect_uri => 'http://www.example.com/oauth2callback',
  :additional_parameters => {
    "access_type" => "offline",         # offline access
    "include_granted_scopes" => "true"  # incremental auth
  }
)

Your application uses the client object to perform OAuth 2.0 operations, such as generating authorization request URLs and applying access tokens to HTTP requests.

HTTP/REST

If you are directly accessing the OAuth 2.0 endpoints, you can proceed to the next step.

Step 2: Redirect to Google's OAuth 2.0 server

When your application needs to access a user's data, redirect the user to Google's OAuth 2.0 server.

PHP

  1. Generate a URL to request access from Google's OAuth 2.0 server:
    $auth_url = $client->createAuthUrl();
  2. Redirect the user to $auth_url:
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

Python

  1. Generate a URL to request access from Google's OAuth 2.0 server:
    auth_uri = flow.step1_get_authorize_url()
  2. Redirect the user to auth_uri.

Ruby

  1. Generate a URL to request access from Google's OAuth 2.0 server:
    auth_uri = auth_client.authorization_uri.to_s
  2. Redirect the user to auth_uri.

HTTP/REST

Generate a URL to request access from Google's OAuth 2.0 endpoint at https://accounts.google.com/o/oauth2/v2/auth. This endpoint is accessible over HTTPS; plain HTTP connections are refused.

The Google authorization server supports the following query string parameters for web server applications:

Parameters
client_id Required. The client ID for your application. You can find this value in the API Console.
redirect_uri Required. Determines where the API server redirects the user after the user completes the authorization flow. The value must exactly match one of the redirect_uri values listed for your project in the API Console. Note that the http or https scheme, case, and trailing slash ('/') must all match.
response_type Required. Determines whether the Google OAuth 2.0 endpoint returns an authorization code. Set the parameter value to code for web server applications.
scope Required. A space-delimited list of scopes that identify the resources that your application could access on the user's behalf. These values inform the consent screen that Google displays to the user.

Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there is an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.

The YouTube Data API uses the following scopes:

Scopes
https://www.googleapis.com/auth/youtubeManage your YouTube account
https://www.googleapis.com/auth/youtube.force-sslManage your YouTube account
https://www.googleapis.com/auth/youtube.readonlyView your YouTube account
https://www.googleapis.com/auth/youtube.uploadManage your YouTube videos
https://www.googleapis.com/auth/youtubepartnerView and manage your assets and associated content on YouTube
https://www.googleapis.com/auth/youtubepartner-channel-auditView private information of your YouTube channel relevant during the audit process with a YouTube partner
The OAuth 2.0 API Scopes document provides a full list of scopes that you might use to access Google APIs.

We recommend that your application request access to authorization scopes in context whenever possible. By requesting access to user data in context, via incremental authorization, you help users to more easily understand why your application needs the access it is requesting.
access_type Recommended. Indicates whether your application can refresh access tokens when the user is not present at the browser. Valid parameter values are online, which is the default value, and offline.

Set the value to offline if your application needs to refresh access tokens when the user is not present at the browser. This is the method of refreshing access tokens described later in this document. This value instructs the Google authorization server to return a refresh token and an access token the first time that your application exchanges an authorization code for tokens.
state Recommended. Specifies any string value that your application uses to maintain state between your authorization request and the authorization server's response. The server returns the exact value that you send as a name=value pair in the hash (#) fragment of the redirect_uri after the user consents to or denies your application's access request.

You can use this parameter for several purposes, such as directing the user to the correct resource in your application, sending nonces, and mitigating cross-site request forgery. Since your redirect_uri can be guessed, using a state value can increase your assurance that an incoming connection is the result of an authentication request. If you generate a random string or encode the hash of a cookie or another value that captures the client's state, you can validate the response to additionally ensure that the request and response originated in the same browser, providing protection against attacks such as cross-site request forgery. See the OpenID Connect documentation for an example of how to create and confirm a state token.
include_granted_scopes Optional. Enables applications to use incremental authorization to request access to additional scopes in context. If you set this parameter's value to true and the authorization request is granted, then the new access token will also cover any scopes to which the user previously granted the application access. See the incremental authorization section for examples.
login_hint Optional. If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to the Google Authentication Server. The server uses the hint to simplify the login flow either by prefilling the email field in the sign-in form or by selecting the appropriate multi-login session.

Set the parameter value to an email address or sub identifier.
prompt Optional. A space-delimited, case-sensitive list of prompts to present the user. If you don't specify this parameter, the user will be prompted only the first time your app requests access. Possible values are:
none Do not display any authentication or consent screens. Must not be specified with other values.
consent Prompt the user for consent.
select_account Prompt the user to select an account.

Sample redirect to Google's authorization server

The sample URL below requests offline access (access_type=offline) to a scope that permits access to view the user's YouTube account. It uses incremental authorization to ensure that the new access token covers any scopes to which the user previously granted the application access. The URL also sets values for the required redirect_uri, response_type, and client_id parameters as well as for the state parameter. The URL contains line breaks and spaces for readability.

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&
 access_type=offline&
 include_granted_scopes=true&
 state=state_parameter_passthrough_value&
 redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
 response_type=code&
 client_id=client_id

After you create the request URL, redirect the user to it.

Google's OAuth 2.0 server authenticates the user and obtains consent from the user for your application to access the requested scopes. The response is sent back to your application using the redirect URL you specified.

Step 3: Google prompts user for consent

In this step, the user decides whether to grant your application the requested access. At this stage, Google displays a consent window that shows the name of your application and the Google API services that it is requesting permission to access with the user's authorization credentials. The user can then consent or refuse to grant access to your application.

Your application doesn't need to do anything at this stage as it waits for the response from Google's OAuth 2.0 server indicating whether the access was granted. That response is explained in the following step.

Step 4: Handle the OAuth 2.0 server response

The OAuth 2.0 server responds to your application's access request by using the URL specified in the request.

If the user approves the access request, then the response contains an authorization code. If the user does not approve the request, the response contains an error message. The authorization code or error message that is returned to the web server appears on the query string, as shown below:

An error response:

https://oauth2.example.com/auth?error=access_denied

An authorization code response:

https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7

Important: If your response endpoint renders an HTML page, any resources on that page will be able to see the authorization code in the URL. Scripts can read the URL directly, and the URL in the Referer HTTP header may be sent to any or all resources on the page.

Carefully consider whether you want to send authorization credentials to all resources on that page (especially third-party scripts such as social plugins and analytics). To avoid this issue, we recommend that the server first handle the request, then redirect to another URL that doesn't include the response parameters.

Sample OAuth 2.0 server response

You can test this flow by clicking on the following sample URL, which requests read-only access to the authenticated user's YouTube account:

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&
 access_type=offline&
 include_granted_scopes=true&
 state=state_parameter_passthrough_value&
 redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
 response_type=code&
 client_id=client_id

After completing the OAuth 2.0 flow, you should be redirected to http://localhost/oauth2callback, which will likely yield a 404 NOT FOUND error unless your local machine serves a file at that address. The next step provides more detail about the information returned in the URI when the user is redirected back to your application.

Step 5: Exchange authorization code for refresh and access tokens

After the web server receives the authorization code, it can exchange the authorization code for an access token.

PHP

To exchange an authorization code for an access token, use the authenticate method:

$client->authenticate($_GET['code']);

You can retrieve the access token with the getAccessToken method:

$access_token = $client->getAccessToken();

Python

To exchange an authorization code for an access token, use the step2_exchange method:

credentials = flow.step2_exchange(auth_code)

Then, use the Credentials object that the step2_exchange method returns to apply the access token to an Http object:

http_auth = credentials.authorize(httplib2.Http())

Ruby

To exchange an authorization code for an access token, use the fetch_access_token! method:

auth_client.code = auth_code
auth_client.fetch_access_token!

HTTP/REST

To exchange an authorization code for an access token, call the https://www.googleapis.com/oauth2/v4/token endpoint and set the following parameters:

Fields
code The authorization code returned from the initial request.
client_id The client ID obtained from the API Console.
client_secret The client secret obtained from the API Console.
redirect_uri One of the redirect URIs listed for your project in the API Console.
grant_type As defined in the OAuth 2.0 specification, this field must contain a value of authorization_code.

The following snippet shows a sample request:

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=https://oauth2.example.com/code&
grant_type=authorization_code

Google responds to this request by returning a JSON object that contains a short-lived access token and a refresh token. Note that the refresh token is only returned if your application set the access_type parameter to offline in the initial request to Google's authorization server.

The response contains the following fields:

Fields
access_token The token that your application sends to authorize a Google API request.
refresh_token A token that you can use to obtain a new access token. Refresh tokens are valid until the user revokes access. Again, this field is only present in this response if you set the access_type parameter to offline in the initial request to Google's authorization server.
expires_in The remaining lifetime of the access token in seconds.
token_type The type of token returned. At this time, this field's value is always set to Bearer.

Important: Your application should store both tokens in a secure, long-lived location that is accessible between different invocations of your application. The refresh token enables your application to obtain a new access token if the one that you have expires. As such, if your application loses the refresh token, the user will need to repeat the OAuth 2.0 consent flow so that your application can obtain a new refresh token.

The following snippet shows a sample response:

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer",
  "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

Calling Google APIs

PHP

Use the access token to call Google APIs by completing the following steps:

  1. If you need to apply an access token to a new Google_Client object—for example, if you stored the access token in a user session—use the setAccessToken method:
    $client->setAccessToken($access_token);
  2. Build a service object for the API that you want to call. You build a a service object by providing an authorized Google_Client object to the constructor for the API you want to call. For example, to call the YouTube Data API:
    $youtube = new Google_Service_YouTube($client);
  3. Make requests to the API service using the interface provided by the service object. For example, to retrieve data about the authorized user's YouTube channel:
    $channel = $youtube->channels->listChannels('snippet', array('mine' => $mine));

Python

Use the authorized Http object to call Google APIs by completing the following steps:

  1. Build a service object for the API that you want to call. You build a service object by calling the build function with the name and version of the API and the authorized Http object. For example, to call version 3 of the YouTube Data API:
    from apiclient.discovery import build
    
    youtube = build('youtube', 'v3', http=http_auth)
  2. Make requests to the API service using the interface provided by the service object. For example, to retrieve data about the authorized user's YouTube channel:
    channel = youtube.channels().list(mine=True, part='snippet').execute()

Ruby

Use the auth_client object to call Google APIs by completing the following steps:

  1. Build a service object for the API that you want to call. For example, to call version 3 of the YouTube Data API:
    youtube = Google::Apis::YoutubeV3::YouTubeService.new
  2. Set the credentials on the service:
    youtube.authorization = auth_client
  3. Make requests to the API service using the interface provided by the service object. For example, to retrieve data about the authorized user's YouTube channel:
    channel = youtube.list_channels(part, :mine => mine)

Alternately, authorization can be provided on a per-method basis by supplying the options parameter to a method:

channel = youtube.list_channels(part, :mine => mine, options: { authorization: auth_client })

HTTP/REST

After your application obtains an access token, you can use the token to make calls to a Google API on behalf of a given user account or service account. To do this, include the access token in a request to the API by including either an access_token query parameter or an Authorization: Bearer HTTP header. When possible, the HTTP header is preferable, because query strings tend to be visible in server logs. In most cases you can use a client library to set up your calls to Google APIs (for example, when calling the YouTube Data API).

Note that the YouTube Data API supports service accounts only for YouTube content owners that own and manage multiple YouTube channels, such as record labels and movie studios.

You can try out all the Google APIs and view their scopes at the OAuth 2.0 Playground.

HTTP GET examples

A call to the youtube.channels endpoint (the YouTube Data API) using the Authorization: Bearer HTTP header might look like the following. Note that you need to specify your own access token:

GET /youtube/v3/channels?part=snippet&mine=true HTTP/1.1
Authorization: Bearer <access_token>
Host: www.googleapis.com/

Here is a call to the same API for the authenticated user using the access_token query string parameter:

GET https://www.googleapis.com/youtube/v3/channels?access_token=<access_token>&part=snippet&mine=true

curl examples

You can test these commands with the curl command-line application. Here's an example that uses the HTTP header option (preferred):

curl -H "Authorization: Bearer <access_token>" https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true

Or, alternatively, the query string parameter option:

curl https://www.googleapis.com/youtube/v3/channels?access_token=<access_token>&part=snippet&mine=true

Complete example

The following example prints a JSON-formatted object showing information about a user's YouTube channel after the user authenticates and authorizes the application to manage the user's YouTube account.

PHP

To run this example:

  1. In the API Console, add the URL of the local machine to the list of redirect URLs. For example, add http://localhost:8080.
  2. Create a new directory and change to it. For example:
    mkdir ~/php-oauth2-example
    cd ~/php-oauth2-example
  3. Install the Google API Client Library for PHP using Composer:
    composer require google/apiclient:^2.0
  4. Create the files index.php and oauth2callback.php with the content below.
  5. Run the example with a web server configured to serve PHP. If you use PHP 5.4 or newer, you can use PHP's built-in test web server:
    php -S localhost:8080 ~/php-oauth2-example

index.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope(GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $youtube = new Google_Service_YouTube($client);
  $channel = $youtube->channels->listChannels('snippet', array('mine' => $mine));
  echo json_encode($channel);
} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

oauth2callback.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL);

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

Python

This example uses the Flask framework.

import json

import flask
import httplib2

from apiclient import discovery
from oauth2client import client


app = flask.Flask(__name__)


@app.route('/')
def index():
  if 'credentials' not in flask.session:
    return flask.redirect(flask.url_for('oauth2callback'))
  credentials = client.OAuth2Credentials.from_json(flask.session['credentials'])
  if credentials.access_token_expired:
    return flask.redirect(flask.url_for('oauth2callback'))
  else:
    http_auth = credentials.authorize(httplib2.Http())
    youtube = discovery.build('youtube', 'v3', http_auth)
    channel = youtube.channels().list(mine=True, part='snippet').execute()
    return json.dumps(channel)


@app.route('/oauth2callback')
def oauth2callback():
  flow = client.flow_from_clientsecrets(
      'client_secrets.json',
      scope='https://www.googleapis.com/auth/youtube.force-ssl',
      redirect_uri=flask.url_for('oauth2callback', _external=True),
      include_granted_scopes=True)
  if 'code' not in flask.request.args:
    auth_uri = flow.step1_get_authorize_url()
    return flask.redirect(auth_uri)
  else:
    auth_code = flask.request.args.get('code')
    credentials = flow.step2_exchange(auth_code)
    flask.session['credentials'] = credentials.to_json()
    return flask.redirect(flask.url_for('index'))


if __name__ == '__main__':
  import uuid
  app.secret_key = str(uuid.uuid4())
  app.debug = False
  app.run()

Ruby

This example uses the Sinatra framework.

require 'google/apis/youtube_v3'
require 'google/api_client/client_secrets'
require 'json'
require 'sinatra'

enable :sessions
set :session_secret, 'setme'

get '/' do
  unless session.has_key?(:credentials)
    redirect to('/oauth2callback')
  end
  client_opts = JSON.parse(session[:credentials])
  auth_client = Signet::OAuth2::Client.new(client_opts)
  youtube = Google::Apis::YoutubeV3::YouTubeService.new
  channel = youtube.list_channels(options: { authorization: auth_client })
  "<pre>#{JSON.pretty_generate(channel.to_h)}</pre>"
end

get '/oauth2callback' do
  client_secrets = Google::APIClient::ClientSecrets.load
  auth_client = client_secrets.to_authorization
  auth_client.update!(
    :scope => 'https://www.googleapis.com/auth/youtube.force-ssl',
    :redirect_uri => url('/oauth2callback'))
  if request['code'] == nil
    auth_uri = auth_client.authorization_uri.to_s
    redirect to(auth_uri)
  else
    auth_client.code = request['code']
    auth_client.fetch_access_token!
    auth_client.client_secret = nil
    session[:credentials] = auth_client.to_json
    redirect to('/')
  end
end

HTTP/REST

This Python example uses the Flask framework and the Requests library to demonstrate the OAuth 2.0 web flow. We recommend using the Google API Client Library for Python for this flow. (The example in the Python tab does use the client library.)

import json

import flask
import requests


app = flask.Flask(__name__)

CLIENT_ID = '123456789.apps.googleusercontent.com'
CLIENT_SECRET = 'abc123'  # Read from a file or environmental variable in a real app
SCOPE = 'https://www.googleapis.com/auth/youtube.force-ssl'
REDIRECT_URI = 'http://example.com/oauth2callback'


@app.route('/')
def index():
  if 'credentials' not in flask.session:
    return flask.redirect(flask.url_for('oauth2callback'))
  credentials = json.loads(flask.session['credentials'])
  if credentials['expires_in'] <= 0:
    return flask.redirect(flask.url_for('oauth2callback'))
  else:
    headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
    req_uri = 'https://www.googleapis.com/youtube/v3/channels/list'
    r = requests.get(req_uri, headers=headers)
    return r.text


@app.route('/oauth2callback')
def oauth2callback():
  if 'code' not in flask.request.args:
    auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
                '&client_id={}&redirect_uri={}&scope={}').format(CLIENT_ID, REDIRECT_URI, SCOPE)
    return flask.redirect(auth_uri)
  else:
    auth_code = flask.request.args.get('code')
    data = {'code': auth_code,
            'client_id': CLIENT_ID,
            'client_secret': CLIENT_SECRET,
            'redirect_uri': REDIRECT_URI,
            'grant_type': 'authorization_code'}
    r = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data)
    flask.session['credentials'] = r.text
    return flask.redirect(flask.url_for('index'))


if __name__ == '__main__':
  import uuid
  app.secret_key = str(uuid.uuid4())
  app.debug = False
  app.run()

Incremental authorization

In the OAuth 2.0 protocol, your app requests authorization to access resources, which are identified by scopes. It is considered a best user-experience practice to request authorization for resources at the time you need them. To enable that practice, Google's authorization server supports incremental authorization. This feature lets you request scopes as they are needed and, if the user grants permission, add those scopes to your existing access token for that user.

For example, suppose an app helps users identify interesting local events. The app lets users view videos about the events, rate the videos, and add the videos to playlists. Users can also use the app to add events to their Google Calendars.

In this case, at sign-in time, the app might not need or request access to any scopes. However, if the user tried to rate a video, add a video to a playlist, or perform another YouTube action, the app could request access to the https://www.googleapis.com/auth/youtube.force-ssl scope. Similarly, the app could request access to the https://www.googleapis.com/auth/calendar scope if the user tried to add a calendar event.

To implement incremental authorization, you complete the normal flow for requesting an access token but make sure that the authorization request includes previously granted scopes. This approach allows your app to avoid having to manage multiple access tokens.

The following rules apply to an access token obtained from an incremental authorization:

  • The token can be used to access resources corresponding to any of the scopes rolled into the new, combined authorization.
  • When you use the refresh token for the combined authorization to obtain an access token, the access token represents the combined authorization and can be used for any of its scopes.
  • The combined authorization includes all scopes that the user granted to the API project even if the grants were requested from different clients. For example, if a user granted access to one scope using an application's desktop client and then granted another scope to the same application via a mobile client, the combined authorization would include both scopes.
  • If you revoke a token that represents a combined authorization, access to all of that authorization's scopes on behalf of the associated user are revoked simultaneously.

The language-specific code samples in Step 1: Configure the client object and the sample HTTP/REST redirect URL in Step 2: Redirect to Google's OAuth 2.0 server all use incremental authorization. The code samples below also show the code that you need to add to use incremental authorization.

PHP

$client->setIncludeGrantedScopes(true);

Python

flow = client.flow_from_clientsecrets(...)
flow.params['include_granted_scopes'] = True

Ruby

auth_client.update!(
  :additional_parameters => {"include_granted_scopes" => "true"}
)

HTTP/REST

In this example, the calling application requests access to retrieve the user's YouTube Analytics data in addition to any other access that the user has already granted to the application.

GET https://accounts.google.com/o/oauth2/v2/auth?
  scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyt-analytics.readonly&
  access_type=offline&
  state=security_token%3D138rk%3Btarget_url%3Dhttp...index&
  redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
  response_type=code&
  client_id=client_id&
  include_granted_scopes=true
  

Refreshing an access token (offline access)

Access tokens periodically expire. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.

  • If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that object for offline access.
  • If you are not using a client library, you need to set the access_type HTTP query parameter to offline when redirecting the user to Google's OAuth 2.0 server. In that case, Google's authorization server returns a refresh token when you exchange an authorization code for an access token. Then, if the access token expires (or at any other time), you can use a refresh token to obtain a new access token.

Requesting offline access is a requirement for any application that needs to access a Google API when the user is not present. For example, an app that performs backup services or executes actions at predetermined times needs to be able to refresh its access token when the user is not present. The default style of access is called online.

Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process. Refresh tokens are not typically used in client-side (JavaScript) web applications.

PHP

If your application needs offline access to a Google API, set the API client's access type to offline:

$client->setAccessType("offline");

After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.

Python

If your application needs offline access to a Google API, set the API client's access type to offline:

flow = client.flow_from_clientsecrets(...)
flow.params['access_type'] = 'offline'

After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.

Ruby

If your application needs offline access to a Google API, set the API client's access type to offline:

auth_client.update!(
  :additional_parameters => {"access_type" => "offline"}
)

After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.

HTTP/REST

To refresh an access token, your application sends an HTTPS POST request to Google's authorization server (https://www.googleapis.com/oauth2/v4/token) that includes the following parameters:

Fields
refresh_token The refresh token returned from the authorization code exchange.
client_id The client ID obtained from the API Console.
client_secret The client secret obtained from the API Console.
grant_type As defined in the OAuth 2.0 specification, this field must contain a value of refresh_token.

The following snippet shows a sample request:

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token

As long as the user has not revoked the access granted to the application, the token server returns a JSON object that contains a new access token. The following snippet shows a sample response:

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer"
}

Note that there are limits on the number of refresh tokens that will be issued; one limit per client/user combination, and another per user across all clients. You should save refresh tokens in long-term storage and continue to use them as long as they remain valid. If your application requests too many refresh tokens, it may run into these limits, in which case older refresh tokens will stop working.

Revoking a token

In some cases a user may wish to revoke access given to an application. A user can revoke access by visiting Account Settings. It is also possible for an application to programmatically revoke the access given to it. Programmatic revocation is important in instances where a user unsubscribes or removes an application. In other words, part of the removal process can include an API request to ensure the permissions granted to the application are removed.

PHP

To programmatically revoke a token, call revokeToken():

$client->revokeToken();

Python

To programmatically revoke a token, call revoke():

credentials.revoke(httplib2.Http())

Ruby

To programmatically revoke a token, make an HTTP request to the oauth2.revoke endpoint:

uri = URI('https://accounts.google.com/o/oauth2/revoke')
params = { :token => auth_client.access_token }
uri.query = URI.encode_www_form(params)
response = Net::HTTP.get(uri)

The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.

If the revocation is successfully processed, then the status code of the response is 200. For error conditions, a status code 400 is returned along with an error code.

HTTP/REST

To programmatically revoke a token, your application makes a request to https://accounts.google.com/o/oauth2/revoke and includes the token as a parameter:

curl -H "Content-type:application/x-www-form-urlencoded" \
        https://accounts.google.com/o/oauth2/revoke?token={token}

The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.

If the revocation is successfully processed, then the status code of the response is 200. For error conditions, a status code 400 is returned along with an error code.

Send feedback about...

YouTube Data API
YouTube Data API