### Setup PHP Project for Google Drive API Source: https://developers.google.com/identity/protocols/oauth2/web-server Commands to set up a new directory, install the Google API Client Library for PHP using Composer, and run the built-in PHP web server. ```bash mkdir ~/php-oauth2-example cd ~/php-oauth2-example ``` ```bash composer require google/apiclient:"^2.15.0" ``` ```bash php -S localhost:8080 ~/php-oauth2-example ``` -------------------------------- ### Install Google API Client Library (Shell) Source: https://developers.google.com/identity/protocols/oauth2/web-server This npm command installs the Google API Client Library for Node.js. It's a required dependency for the example. ```shell npm install googleapis ``` -------------------------------- ### Create Project Directory (Shell) Source: https://developers.google.com/identity/protocols/oauth2/web-server This shell command creates a new directory for the Node.js OAuth 2.0 example and changes into it. Ensure you have Node.js installed. ```shell mkdir ~/nodejs-oauth2-example cd ~/nodejs-oauth2-example ``` -------------------------------- ### Install Google Auth Library for Ruby Source: https://developers.google.com/identity/protocols/oauth2/web-server Install the Google Auth Library for Ruby using the gem command. This library is essential for handling authentication. ```bash gem install googleauth ``` -------------------------------- ### Run Node.js Example (Shell) Source: https://developers.google.com/identity/protocols/oauth2/web-server This command executes the Node.js OAuth 2.0 example using the Node.js runtime. Make sure the 'main.js' file is in the current directory. ```shell node .\main.js ``` -------------------------------- ### Install Sinatra for Ruby Web Applications Source: https://developers.google.com/identity/protocols/oauth2/web-server Install the Sinatra Ruby web application framework using gem. Sinatra is a lightweight framework for building web applications. ```bash gem install sinatra ``` -------------------------------- ### Install Google APIs Client Libraries for Ruby Source: https://developers.google.com/identity/protocols/oauth2/web-server Install the client libraries for Google Drive and Calendar APIs for Ruby using gem. These libraries provide access to specific Google services. ```bash gem install google-apis-drive_v3 google-apis-calendar_v3 ``` -------------------------------- ### Install Google Auth Libraries for Python Source: https://developers.google.com/identity/protocols/oauth2/web-server Install the necessary Google authentication libraries for Python using pip. These are required for user authorization. ```bash pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2 ``` -------------------------------- ### Install Google APIs Client Library for PHP Source: https://developers.google.com/identity/protocols/oauth2/web-server Use Composer to install the Google APIs Client Library for PHP. Ensure you are using PHP 8.0 or greater. ```bash composer require google/apiclient:^2.15.0 ``` -------------------------------- ### iOS App Store ID Example Source: https://developers.google.com/identity/protocols/oauth2/native-app Example URL demonstrating how to extract the App Store ID for an iOS application. ```text https://apps.apple.com/app/google/id284815942 ``` -------------------------------- ### Install Google APIs Client Library for Python Source: https://developers.google.com/identity/protocols/oauth2/web-server Use pip to install the Google APIs Client Library for Python 2.0. Ensure you are using Python 3.7 or greater. ```bash pip install --upgrade google-api-python-client ``` -------------------------------- ### Access Token Response Example Source: https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow This is an example of an access token response, showing the granted scopes. It's useful for understanding the structure of the response when checking user permissions. ```json { "access_token": "1/fFAGRNJru1FTz70BzhT3Zg", "expires_in": 3920, "token_type": "Bearer", "scope": "https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.readonly", "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI" } ``` -------------------------------- ### Install Google APIs Node.js Client and Dependencies Source: https://developers.google.com/identity/protocols/oauth2/web-server Install the Google APIs Node.js Client along with 'crypto', 'express', and 'express-session' using npm. These are required for Node.js applications interacting with Google APIs. ```bash npm install googleapis crypto express express-session ``` -------------------------------- ### Example OpenID Connect Discovery Document Source: https://developers.google.com/identity/protocols/oauth2/openid-connect An example of Google's Discovery document, showing key-value pairs that provide details about the OpenID Connect provider's configuration. This document is used to dynamically discover endpoint URIs. ```json { "issuer": "https://accounts.google.com", "authorization_endpoint": "https://accounts.google.com/o/oauth2/v2/auth", "device_authorization_endpoint": "https://oauth2.googleapis.com/device/code", "token_endpoint": "https://oauth2.googleapis.com/token", "userinfo_endpoint": "https://openidconnect.googleapis.com/v1/userinfo", "revocation_endpoint": "https://oauth2.googleapis.com/revoke", "jwks_uri": "https://www.googleapis.com/oauth2/v3/certs", "response_types_supported": [ "code", "token", "id_token", "code token", "code id_token", "token id_token", "code token id_token", "none" ], "subject_types_supported": [ "public" ], "id_token_signing_alg_values_supported": [ "RS256" ], "scopes_supported": [ "openid", "email", "profile" ], "token_endpoint_auth_methods_supported": [ "client_secret_post", "client_secret_basic" ], "claims_supported": [ "aud", "email", "email_verified", "exp", "family_name", "given_name", "iat", "iss", "locale", "name", "picture", "sub" ], "code_challenge_methods_supported": [ "plain", "S256" ] } ``` -------------------------------- ### Install Requests HTTP Library for Python Source: https://developers.google.com/identity/protocols/oauth2/web-server Install the 'requests' HTTP library for Python using pip. This library simplifies making HTTP requests. ```bash pip install --upgrade requests ``` -------------------------------- ### Error Response Example Source: https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow An example of an OAuth 2.0 error response, such as 'access_denied', returned on the hash fragment of the redirect URI. This indicates the user did not approve the request. ```url https://oauth2.example.com/callback#error=access_denied ``` -------------------------------- ### Install Flask for Python Web Applications Source: https://developers.google.com/identity/protocols/oauth2/web-server Install the Flask web application framework for Python using pip. This is commonly used for building web applications that interact with Google APIs. ```bash pip install --upgrade flask ``` -------------------------------- ### Access Token Response Example Source: https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow An example of a successful OAuth 2.0 response containing an access token, token type, and expiration time. This is returned on the hash fragment of the redirect URI. ```url https://oauth2.example.com/callback#access_token=4/P7q7W91&token_type=Bearer&expires_in=3600 ``` -------------------------------- ### Example JWT Header and Claim Set (Unsigned) Source: https://developers.google.com/identity/protocols/oauth2/service-account Illustrates the structure of a JWT header and claim set before Base64url encoding and signing. ```json {"alg":"RS256","typ":"JWT"}. { "iss":"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com", "scope":"https://www.googleapis.com/auth/prediction", "aud":"https://oauth2.googleapis.com/token", "exp":1328554385, "iat":1328550785 }. [signature bytes] ``` -------------------------------- ### Python Flask OAuth 2.0 Setup Source: https://developers.google.com/identity/protocols/oauth2/web-server Initializes a Flask application for OAuth 2.0 testing, setting up necessary files and scopes. Requires `client_secret.json` and specifies the redirect URI. ```python # -*- coding: utf-8 -*- import os import flask import json import requests import google.oauth2.credentials import google_auth_oauthlib.flow import googleapiclient.discovery # This variable specifies the name of a file that contains the OAuth 2.0 # information for this application, including its client_id and client_secret. CLIENT_SECRETS_FILE = "client_secret.json" # The OAuth 2.0 access scope allows for access to the ``` -------------------------------- ### Revoke Token Request Setup Source: https://developers.google.com/identity/protocols/oauth2/web-server This snippet shows the initial setup for revoking a user's access token. It prepares the data payload required for the POST request to Google's OAuth 2.0 server. ```javascript // Example on revoking a token app.get('/revoke', async (req, res) => { // Build the string for the POST request let postData = "token=" + userCredential.access_token; // Options for POST request to Google's OAuth 2.0 server to revoke a token let postOptions = { ``` -------------------------------- ### Curl Command for Token Request Source: https://developers.google.com/identity/protocols/oauth2/limited-input-device This example demonstrates how to send the polling request using `curl`. It includes the necessary data and headers for the request. ```curl curl -d "client_id=client_id&client_secret=client_secret& \ device_code=device_code& \ grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code" \ -H "Content-Type: application/x-www-form-urlencoded" \ https://oauth2.googleapis.com/token ``` -------------------------------- ### API Call with Bearer Token Source: https://developers.google.com/identity/protocols/oauth2/service-account Example of an HTTP GET request to a Google API using a signed JWT as the bearer token in the Authorization header. ```http GET /v1/projects/abc/databases/123/indexes HTTP/1.1 Authorization: Bearer SIGNED_JWT Host: firestore.googleapis.com ``` -------------------------------- ### Node.js Main Function Execution Source: https://developers.google.com/identity/protocols/oauth2/web-server An asynchronous main function that orchestrates the server setup and execution, catching any top-level errors. It's designed to be called once to start the application. ```javascript main().catch(console.error); ``` -------------------------------- ### Initialize OAuth2 Client and Define Scopes Source: https://developers.google.com/identity/protocols/oauth2/web-server Set up the OAuth2 client with your credentials and define the necessary API scopes. Ensure you replace placeholder values with your actual client ID, client secret, and redirect URL. ```javascript const http = require('http'); const https = require('https'); const url = require('url'); const { google } = require('googleapis'); const crypto = require('crypto'); const express = require('express'); const session = require('express-session'); /** * To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI. * To get these credentials for your application, visit * https://console.cloud.google.com/apis/credentials. */ const oauth2Client = new google.auth.OAuth2( YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, YOUR_REDIRECT_URL ); // Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar. const scopes = [ 'https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/calendar.readonly' ]; /* Global variable that stores user credential in this code example. * ACTION ITEM for developers: * Store user's refresh token in your data store if * incorporating this code into your real app. * For more information on handling refresh tokens, * see https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens */ let userCredential = null; ``` -------------------------------- ### GET Request to Drive Files API with Authorization Header Source: https://developers.google.com/identity/protocols/oauth2/limited-input-device Example of calling the Drive Files API using the Authorization: Bearer HTTP header. Ensure your access token is correctly specified. ```http GET /drive/v2/files HTTP/1.1 Host: www.googleapis.com **Authorization: Bearer access_token** ``` -------------------------------- ### GET Request to Drive Files API with Access Token Query Parameter Source: https://developers.google.com/identity/protocols/oauth2/limited-input-device Example of calling the Drive Files API using the access_token query string parameter. This method is less preferred due to potential visibility in server logs. ```http GET https://www.googleapis.com/drive/v2/files?access_token=access_token ``` -------------------------------- ### Ruby: Initialize OAuth 2.0 Client and Scopes Source: https://developers.google.com/identity/protocols/oauth2/web-server Sets up the OAuth 2.0 client using credentials from a local file and defines the necessary API scopes. A Redis token store is configured for managing tokens. ```ruby require 'googleauth' require 'googleauth/web_user_authorizer' require 'googleauth/stores/redis_token_store' require 'google/apis/drive_v3' require 'google/apis/calendar_v3' client_id = Google::Auth::ClientId.from_file('/path/to/client_secret.json') scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY', 'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY'] token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new) callback_uri = '/oauth2callback' ``` -------------------------------- ### OAuth 2.0 Authorization Code Response Example Source: https://developers.google.com/identity/protocols/oauth2/web-server This is an example of a successful authorization code response from the OAuth 2.0 server. ```url https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7 ``` -------------------------------- ### Set Credentials and List Files in Drive using Ruby Source: https://developers.google.com/identity/protocols/oauth2/web-server Set credentials on the Drive service object and then make requests to list files in the authenticated user's Google Drive. ```ruby drive.authorization = credentials files = drive.list_files ``` -------------------------------- ### Initialize Google Auth Components (Ruby/Sinatra) Source: https://developers.google.com/identity/protocols/oauth2/web-server This snippet initializes the necessary Google Auth components for a Sinatra application, including the Client ID, scopes, token store (Redis), and callback URI. It requires a 'client_secret.json' file and a Redis instance. ```ruby configure do enable :sessions # Required, call the from_file method to retrieve the client ID from a # client_secret.json file. set :client_id, Google::Auth::ClientId.from_file('/path/to/client_secret.json') # Required, scope value # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar. scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY', 'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY'] # Required, Authorizers require a storage instance to manage long term persistence of # access and refresh tokens. set :token_store, Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new) # Required, indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI is required. The value must exactly # match one of the authorized redirect URIs for the OAuth 2.0 client, which you # configured in the API Console. If this value doesn't match an authorized URI, # you will get a 'redirect_uri_mismatch' error. set :callback_uri, '/oauth2callback' end ``` -------------------------------- ### Initialize Google Auth WebUserAuthorizer Source: https://developers.google.com/identity/protocols/oauth2/web-server Initializes the Google::Auth::WebUserAuthorizer with client ID, scope, token store, and callback URI. Ensure you have obtained these credentials from the Google Cloud Console. ```ruby set :authorizer, Google::Auth::WebUserAuthorizer.new(settings.client_id, settings.scope, settings.token_store, callback_uri: settings.callback_uri) ``` -------------------------------- ### PHP Example: List Google Drive Files Source: https://developers.google.com/identity/protocols/oauth2/web-server This PHP script authenticates a user, checks for Drive and Calendar permissions, and lists files from Google Drive if permission is granted. It requires the Google API Client Library for PHP and a 'client_secret.json' file. ```php setAuthConfig('client_secret.json'); // User granted permission as an access token is in the session. if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { $client->setAccessToken($_SESSION['access_token']); // Check if user granted Drive permission if ($_SESSION['granted_scopes_dict']['Drive']) { echo "Drive feature is enabled."; echo "
"; $drive = new Drive($client); $files = array(); $response = $drive->files->listFiles(array()); foreach ($response->files as $file) { echo "File: " . $file->name . " (" . $file->id . ")"; echo "
"; } } else { echo "Drive feature is NOT enabled."; echo "
"; } // Check if user granted Calendar permission if ($_SESSION['granted_scopes_dict']['Calendar']) { echo "Calendar feature is enabled."; echo "
"; } else { echo "Calendar feature is NOT enabled."; echo "
"; } } else { // Redirect users to outh2call.php which redirects users to Google OAuth 2.0 $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); } ?> ``` -------------------------------- ### Python: Initialize OAuth 2.0 Flow Source: https://developers.google.com/identity/protocols/oauth2/web-server Initializes an OAuth 2.0 flow from a client secrets file and defines the redirect URI. Ensure 'client_secret.json' is in the same directory or provide the correct path. ```python import google_auth_oauthlib.flow flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_secret.json', scopes=['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/calendar.readonly']) flow.redirect_uri = 'https://www.example.com/oauth2callback' ``` -------------------------------- ### Create Service Account Credentials (Python) Source: https://developers.google.com/identity/protocols/oauth2/service-account Use the Google Auth Library for Python to create a Credentials object from a service account's JSON key file and specify the required scopes. ```python from google.oauth2 import service_account SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin'] SERVICE_ACCOUNT_FILE = '/path/to/ServiceAccountKey.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) ``` -------------------------------- ### JWT Header and Payload Example Source: https://developers.google.com/identity/protocols/oauth2/service-account Example of the header and payload structure for a JWT used for service account authorization. Ensure 'kid' matches your private key ID and 'iss'/'sub' match your service account email. ```json { "alg": "RS256", "typ": "JWT", "kid": "abcdef1234567890" } . { "iss": "123456-compute@developer.gserviceaccount.com", "sub": "123456-compute@developer.gserviceaccount.com", "aud": "https://firestore.googleapis.com/", "iat": 1511900000, "exp": 1511903600 } ``` -------------------------------- ### List Cloud SQL Instances (Java) Source: https://developers.google.com/identity/protocols/oauth2/service-account Make a request to the Cloud SQL Admin API to list instances for a specific project using the service object created previously. ```java SQLAdmin.Instances.List instances = sqladmin.instances().list("exciting-example-123").execute(); ``` -------------------------------- ### List Cloud SQL Instances (Python) Source: https://developers.google.com/identity/protocols/oauth2/service-account Make a request to the Cloud SQL Admin API to list instances for a specific project using the service object created previously. ```python response = sqladmin.instances().list(project='exciting-example-123').execute() ``` -------------------------------- ### Initialize Flask Application Source: https://developers.google.com/identity/protocols/oauth2/web-server Initialize a Flask application instance. A secret key is included for demonstration purposes; replace it with a secure, unique key for production environments. ```python import flask app = flask.Flask(__name__) # Note: A secret key is included in the sample so that it works. # If you use this code in your application, replace this with a truly secret ``` -------------------------------- ### Example Signed JWT Source: https://developers.google.com/identity/protocols/oauth2/service-account A complete JWT that has been signed and is ready for transmission to the authorization server. ```text eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI3NjEzMjY3OTgwNjktcjVtbGpsbG4xcmQ0bHJiaGc3NWVmZ2lncDM2bTc4ajVAZGV2ZWxvcGVyLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzY29wZSI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvcHJlZGljdGlvbiIsImF1ZCI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL29hdXRoMi92NC90b2tlbiIsImV4cCI6MTMyODU1NDM4NSwiaWF0IjoxMzI4NTUwNzg1fQ.UFUt59SUM2_AW4cRU8Y0BYVQsNTo4n7AFsNrqOpYiICDu37vVt-tw38UKzjmUKtcRsLLjrR3gFW3dNDMx_pL9DVjgVHDdYirtrCekUHOYoa1CMR66nxep5q5cBQ4y4u2kIgSvChCTc9pmLLNoIem-ruCecAJYgI9Ks7pTnW1gkOKs0x3YpiLpzplVHAkkHztaXiJdtpBcY1OXyo6jTQCa3Lk2Q3va1dPkh_d--GU2M5flgd8xNBPYw4vxyt0mP59XZlHMpztZt0soSgObf7G3GXArreF_6tpbFsS3z2t5zkEiHuWJXpzcYr5zWTRPDEHsejeBSG8EgpLDce2380ROQ ``` -------------------------------- ### JWT Claim Set Example for Encoding Source: https://developers.google.com/identity/protocols/oauth2/service-account A sample JWT claim set demonstrating the structure before Base64url encoding. ```json { "iss": "761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com", "scope": "https://www.googleapis.com/auth/prediction", "aud": "https://oauth2.googleapis.com/token", "exp": 1328554385, "iat": 1328550785 } ``` -------------------------------- ### Sensitive Scope Justification Example Source: https://developers.google.com/identity/protocols/oauth2/production-readiness/sensitive-scope-verification Provide a clear explanation for why a sensitive scope is necessary and how it will be used within your application. ```text My app will use `https://www.googleapis.com/auth/calendar` to show a user's Google calendar data on the scheduling screen of my app. This lets users manage their schedules through my app and sync the changes with their Google calendar. ``` -------------------------------- ### JWT Header Example Source: https://developers.google.com/identity/protocols/oauth2/service-account The JSON representation of a JWT header for service accounts, specifying the signing algorithm and token type. ```json {"alg":"RS256","typ":"JWT", "kid":"370ab79b4513eb9bad7c9bd16a95cb76b5b2a56a"} ```