### gapi.auth2.init Parameters Example Source: https://developers.google.com/identity/sign-in/web/reference Example of parameters for initializing the GoogleAuth object with a client ID. ```json { client_id: 'CLIENT_ID.apps.googleusercontent.com' } ``` -------------------------------- ### gapi.signin2.render Options Example Source: https://developers.google.com/identity/sign-in/web/reference An example of the options object used to configure the sign-in button rendered by `gapi.signin2.render`. ```javascript { scope: 'email', width: 200, height: 50, longtitle: true, theme: 'dark', onsuccess: handleSuccess, onfailure: handleFailure } ``` -------------------------------- ### Run PHP Built-in Web Server Source: https://developers.google.com/identity/protocols/oauth2/web-server Start the PHP built-in web server to host your OAuth 2.0 example application. This command binds the server to localhost on port 8080. ```bash php -S localhost:8080 ~/php-oauth2-example ``` -------------------------------- ### gapi.auth2.authorize Configuration Example Source: https://developers.google.com/identity/sign-in/web/reference An example of the parameters object used for one-time OAuth 2.0 authorization with `gapi.auth2.authorize`. ```javascript { client_id: 'CLIENT_ID.apps.googleusercontent.com', scope: 'email profile openid', response_type: 'id_token permission' } ``` -------------------------------- ### Install Dependencies with CocoaPods Source: https://developers.google.com/identity-toolkit/v3 After modifying the Podfile, run this command to install the dependencies. ```bash pod install ``` -------------------------------- ### signIn(withPresentingWindow:hint:completion:) Source: https://developers.google.com/identity/sign-in/ios/reference/Classes/GIDSignIn.html Starts an interactive sign-in flow on macOS using a provided window and an optional hint. This method is suitable for initiating sign-in when the app is not starting up. ```APIDOC ## signIn(withPresentingWindow:hint:completion:) ### Description Starts an interactive sign-in flow on macOS using the provided hint. The completion block is called at the end of this process. Any saved sign-in state will be replaced by the result of this flow. This method should not be called when the app is starting up; use `restorePreviousSignInWithCompletion:` instead. ### Method Objective-C ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example Objective-C: ```objc - (void)signInWithPresentingWindow:(id)presentingWindow hint:(nullable NSString *)hint completion: (nullable void (^)(GIDSignInResult *_Nullable, NSError *_Nullable))completion; ``` Swift: ```swift func signIn(withPresentingWindow presentingWindow: Any!, hint: String?) async throws -> GIDSignInResult ``` #### Parameters * `_presentingWindow_` (Any!) - The window used to supply `presentationContextProvider` for `ASWebAuthenticationSession`. * `_hint_` (NSString?) - An optional hint for the authorization server, for example the user’s ID or email address, to be prefilled if possible. * `_completion_` (void (^)(GIDSignInResult *_Nullable, NSError *_Nullable)) - The optional block that is called on completion. This block will be called asynchronously on the main queue. ### Response #### Success Response - `GIDSignInResult` - The result of the sign-in operation. #### Response Example N/A (Completion block handles results) ``` -------------------------------- ### Install Node.js Google Auth Library Source: https://developers.google.com/identity/gsi/web/guides/verify-google-id-token Install the Google Auth Library for Node.js using npm. This library is required to verify ID tokens. ```bash npm install google-auth-library --save ``` -------------------------------- ### Start Interactive Sign-In with Hint (macOS) Source: https://developers.google.com/identity/sign-in/ios/reference/Classes/GIDSignIn.html Starts an interactive sign-in flow on macOS with an optional hint for the authorization server. This method should not be called during app startup. ```objc - (void)signInWithPresentingWindow:(id)presentingWindow hint:(nullable NSString *)hint completion: (nullable void (^)(GIDSignInResult *_Nullable, NSError *_Nullable))completion; ``` -------------------------------- ### 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 required for authentication with Google APIs. ```bash gem install googleauth ``` -------------------------------- ### Install Firebase SDK Source: https://developers.google.com/identity/toolkit/migrate-firebase After adding the Firebase pod to your Podfile, run 'pod install' to integrate the SDK into your Xcode project. ```bash pod install ``` -------------------------------- ### Install Google API 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. Ensure you are using Python 3.7 or greater. ```bash pip install --upgrade google-api-python-client ``` -------------------------------- ### 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 PHP Google API Client Library Source: https://developers.google.com/identity/gsi/web/guides/verify-google-id-token Install the Google API Client Library for PHP using Composer. This library is needed to verify ID tokens in PHP applications. ```bash composer require google/apiclient ``` -------------------------------- ### Install Sinatra for Ruby Web Applications Source: https://developers.google.com/identity/protocols/oauth2/web-server Install the Sinatra web application framework for Ruby using gem. Sinatra is a lightweight framework often used for building web applications. ```bash gem install sinatra ``` -------------------------------- ### Start Interactive Sign-In with Hint and Scopes (macOS) Source: https://developers.google.com/identity/sign-in/ios/reference/Classes/GIDSignIn.html Starts an interactive sign-in flow on macOS, accepting a hint and an array of additional scopes. This method is intended for use when the app is not initializing. ```objc - (void)signInWithPresentingWindow:(id)presentingWindow hint:(nullable NSString *)hint additionalScopes: (nullable NSArray *)additionalScopes completion: (nullable void (^)(GIDSignInResult *_Nullable, NSError *_Nullable))completion; ``` -------------------------------- ### Example GET Request with Authorization Code Source: https://developers.google.com/identity/oauth2/web/guides/use-code-model This is an example of a GET request to an authorization endpoint, including URL parameters like state, code, scope, and user information. Clients must ignore unrecognized parameters. ```http Request URL: https://www.example.com/auth-code?state=42a7bd822fe32cc56&code=4/0AX4XfWiAvnXLqxlckFUVao8j0zvZUJ06AMgr-n0vSPotHWcn9p-zHCjqwr47KHS_vDvu8w&scope=email%20profile%20https://www.googleapis.com/auth/calendar.readonly%20https://www.googleapis.com/auth/photoslibrary.readonly%20https://www.googleapis.com/auth/contacts.readonly%20openid%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&authuser=0&hd=example.com&prompt=consent ``` -------------------------------- ### Create Project Directory Source: https://developers.google.com/identity/protocols/oauth2/web-server Create a new directory for your OAuth 2.0 example and navigate into it. This is a prerequisite for setting up the project. ```bash mkdir ~/php-oauth2-example cd ~/php-oauth2-example ``` -------------------------------- ### Userinfo Endpoint Request Example Source: https://developers.google.com/identity/account-linking/oauth-linking Example of an HTTP GET request to the userinfo endpoint, including the Authorization header with a Bearer token. ```http GET /userinfo HTTP/1.1 Host: myservice.example.com Authorization: Bearer ACCESS_TOKEN ``` -------------------------------- ### Google Sign-In Initialization and Listener Setup Source: https://developers.google.com/identity/sign-in/web/listeners Initializes the Google Sign-In v2 library and sets up listeners for sign-in state and user changes. This code should be called after the gapi library is loaded. ```javascript var auth2; var googleUser; /** * Calls startAuth after Sign in V2 finishes setting up. */ var appStart = function() { gapi.load('auth2', initSigninV2); }; /** * Initializes Signin v2 and sets up listeners. */ var initSigninV2 = function() { auth2 = gapi.auth2.init({ client_id: 'CLIENT_ID.apps.googleusercontent.com', scope: 'profile' }); // Listen for sign-in state changes. auth2.isSignedIn.listen(signinChanged); // Listen for changes to current user. auth2.currentUser.listen(userChanged); // Sign in the user if they are currently signed in. if (auth2.isSignedIn.get() == true) { auth2.signIn(); } // Start with the current live values. refreshValues(); }; /** * Listener method for sign-out live value. * * @param {boolean} val the updated signed out state. */ var signinChanged = function (val) { console.log('Signin state changed to ', val); document.getElementById('signed-in-cell').innerText = val; }; /** * Listener method for when the user changes. * * @param {GoogleUser} user the updated user. */ var userChanged = function (user) { console.log('User now: ', user); googleUser = user; updateGoogleUser(); document.getElementById('curr-user-cell').innerText = JSON.stringify(user, undefined, 2); }; /** * Updates the properties in the Google User table using the current user. */ var updateGoogleUser = function () { if (googleUser) { document.getElementById('user-id').innerText = googleUser.getId(); document.getElementById('user-scopes').innerText = googleUser.getGrantedScopes(); document.getElementById('auth-response').innerText = JSON.stringify(googleUser.getAuthResponse(), undefined, 2); } else { document.getElementById('user-id').innerText = '--'; document.getElementById('user-scopes').innerText = '--'; document.getElementById('auth-response').innerText = '--'; } }; /** * Retrieves the current user and signed in states from the GoogleAuth * object. */ var refreshValues = function() { if (auth2){ console.log('Refreshing values...'); googleUser = auth2.currentUser.get(); document.getElementById('curr-user-cell').innerText = JSON.stringify(googleUser, undefined, 2); document.getElementById('signed-in-cell').innerText = auth2.isSignedIn.get(); updateGoogleUser(); } } ``` -------------------------------- ### Start SMS Retriever Client Source: https://developers.google.com/identity/sms-retriever/request Get an instance of SmsRetrieverClient and start listening for a matching SMS message. The retriever waits for one SMS message for up to 5 minutes. ```java SmsRetrieverClient client = SmsRetriever.getClient(this /* context */); Task task = client.startSmsRetriever(); task.addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { // Successfully started retriever, expect broadcast intent // ... } }); task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Failed to start retriever, inspect Exception for more details // ... } }); ``` -------------------------------- ### OAuth 2.0 Web Server Flow Example in Python (Flask) Source: https://developers.google.com/identity/protocols/oauth2/web-server This Python Flask application demonstrates the complete OAuth 2.0 web server flow, including user authorization, token exchange, and making authenticated API calls. Ensure you have Flask and Requests installed (`pip install Flask requests`). ```python import json import flask import requests app = flask.Flask(__name__) # To get these credentials (CLIENT_ID CLIENT_SECRET) and for your application, visit # https://console.cloud.google.com/apis/credentials. CLIENT_ID = '123456789.apps.googleusercontent.com' CLIENT_SECRET = 'abc123' # Read from a file or environmental variable in a real app # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar. SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.readonly' # 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. 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: # User authorized the request. Now, check which scopes were granted. if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['scope']: # User authorized read-only Drive activity permission. # Example of using Google Drive API to list filenames in user's Drive. headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])} req_uri = 'https://www.googleapis.com/drive/v2/files' r = requests.get(req_uri, headers=headers).text else: # User didn't authorize read-only Drive activity permission. # Update UX and application accordingly r = 'User did not authorize Drive permission.' # Check if user authorized Calendar read permission. if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['scope']: # User authorized Calendar read permission. # Calling the APIs, etc. r += 'User authorized Calendar permission.' else: # User didn't authorize Calendar read permission. # Update UX and application accordingly r += 'User did not authorize Calendar permission.' return r @app.route('/oauth2callback') def oauth2callback(): if 'code' not in flask.request.args: state = str(uuid.uuid4()) flask.session['state'] = state # Generate a url that asks permissions for the Drive activity # and Google Calendar scope. Then, redirect user to the url. auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code' '&client_id={}&redirect_uri={}&scope={}&state={}').format(CLIENT_ID, REDIRECT_URI, SCOPE, state) return flask.redirect(auth_uri) else: if 'state' not in flask.request.args or flask.request.args['state'] != flask.session['state']: return 'State mismatch. Possible CSRF attack.', 400 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'} # Exchange authorization code for access and refresh tokens (if access_type is offline) r = requests.post('https://oauth2.googleapis.com/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() ``` -------------------------------- ### Initialize Google Sign-In and App Check Source: https://developers.google.com/identity/sign-in/ios/appcheck/get-started In your app delegate's `didFinishLaunchingWithOptions` method, call `GIDSignIn.sharedInstance.configure` for production or `GIDSignIn.sharedInstance.configureDebugProvider` for testing. This should be called early in the app lifecycle. ```swift import SwiftUI import GoogleSignIn class AppDelegate: NSObject, UIApplicationDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil ) -> Bool { #if targetEnvironment(simulator) // Configure for debugging. // See: https://developers.google.com/identity/sign-in/ios/appcheck/debug-provider #else GIDSignIn.sharedInstance.configure { error in if let error { print("Error configuring `GIDSignIn` for Firebase App Check: \(error)") } } #endif return true } } @main struct YourAppNameApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate // ... } ``` -------------------------------- ### HTTP GET Request using Authorization Header Source: https://developers.google.com/identity/protocols/oauth2/native-app Example of calling the Drive Files API using the 'Authorization: Bearer' HTTP header. This method is preferred over query string parameters. ```http GET /drive/v2/files HTTP/1.1 Host: www.googleapis.com Authorization: Bearer access_token ``` -------------------------------- ### Sign In with Presenting Window and Hint Source: https://developers.google.com/identity/sign-in/ios/reference/Classes/GIDSignIn.html Initiates the Google sign-in flow with a hint, using a presenting window. ```APIDOC ## -signInWithPresentingWindow:hint:completion: ### Description Initiates the Google sign-in flow with an optional hint, presenting the sign-in UI modally using a window. ### Method Instance Method ### Endpoint N/A (Instance Method) ### Parameters - **presentingWindow** (UIWindow) - The window that will present the sign-in UI. - **hint** (NSString) - An optional hint for the sign-in process (e.g., user's email). - **completion** (GIDSignInCallback) - A block that is executed upon completion of the sign-in operation. It receives a GIDGoogleUser object and an error if one occurred. ### Response None ``` -------------------------------- ### Get Auth Token using Chrome Identity API Source: https://developers.google.com/identity/protocols/oauth2/resources/oob-migration Retrieve an access token for a Chrome App client using the Chrome Identity API. This example demonstrates interactive token retrieval. ```javascript window.onload = function() { document.querySelector('button').addEventListener('click', function() { ** // retrieve access token chrome.identity.getAuthToken({interactive: true}, function(token) { ** // .......... // the example below shows how to use a retrieved access token with an appropriate scope // to call the Google People API contactGroups.get endpoint fetch( 'https://people.googleapis.com/v1/contactGroups/all?maxMembers=20&key=API_KEY', init) .then((response) => response.json()) .then(function(data) { console.log(data) }); }); }); }; ``` -------------------------------- ### Configure One Tap Prompt Login Hint Source: https://developers.google.com/identity/gsi/web/guides/handle-credential-responses-js-functions Provide a login hint for the One Tap prompt using HTML attributes. This example sets the login hint to 'user@example.com'. ```html ``` -------------------------------- ### API Call with Signed JWT 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 Authorization bearer token. Ensure the 'Authorization' header is correctly formatted. ```http GET /v1/projects/abc/databases/123/indexes HTTP/1.1 Authorization: Bearer SIGNED_JWT Host: firestore.googleapis.com ``` -------------------------------- ### Initialize and Prompt with Google Accounts Source: https://developers.google.com/identity/gsi/web/reference/js-reference Implement the `onGoogleLibraryLoad` callback to initialize Google accounts and prompt the user. This code should be placed within a script tag. ```html ``` -------------------------------- ### Sign In with Presenting View Controller and Hint Source: https://developers.google.com/identity/sign-in/ios/reference/Classes/GIDSignIn.html Initiates the Google sign-in flow with a hint, using a presenting view controller. ```APIDOC ## -signInWithPresentingViewController:hint:completion: ### Description Initiates the Google sign-in flow with an optional hint, presenting the sign-in UI modally. ### Method Instance Method ### Endpoint N/A (Instance Method) ### Parameters - **presentingViewController** (UIViewController) - The view controller that will present the sign-in UI. - **hint** (NSString) - An optional hint for the sign-in process (e.g., user's email). - **completion** (GIDSignInCallback) - A block that is executed upon completion of the sign-in operation. It receives a GIDGoogleUser object and an error if one occurred. ### Response None ``` -------------------------------- ### Get Auth Token and Call Google People API (Chrome App) Source: https://developers.google.com/identity/protocols/oauth2/resources/loopback-migration Retrieve an access token using chrome.identity.getAuthToken and use it to call the Google People API's contactGroups.get endpoint. This example demonstrates accessing contacts without a loopback IP address redirect URI. ```javascript window.onload = function() { document.querySelector('button').addEventListener('click', function() { // retrieve access token chrome.identity.getAuthToken({interactive: true}, function(token) { // the example below shows how to use a retrieved access token with an appropriate scope // to call the Google People API contactGroups.get endpoint fetch( 'https://people.googleapis.com/v1/contactGroups/all?maxMembers=20&key=API_KEY', init) .then((response) => response.json()) .then(function(data) { console.log(data) }); }); }); }; ``` -------------------------------- ### Create and Launch Hint Request Source: https://developers.google.com/identity/smartlock-passwords/android/retrieve-hints Configure a HintRequest to prompt the user to choose an email address. Pass this request to getHintPickerIntent and then start the intent sender. ```java HintRequest hintRequest = new HintRequest.Builder() .setHintPickerConfig(new CredentialPickerConfig.Builder() .setShowCancelButton(true) .build()) .setEmailAddressIdentifierSupported(true) .setAccountTypes(IdentityProviders.GOOGLE) .build(); PendingIntent intent = mCredentialsClient.getHintPickerIntent(hintRequest); try { startIntentSenderForResult(intent.getIntentSender(), RC_HINT, null, 0, 0, 0); } catch (IntentSender.SendIntentException e) { Log.e(TAG, "Could not start hint picker Intent", e); } ``` -------------------------------- ### Initialize GAPI and GIS with Token Model Source: https://developers.google.com/identity/oauth2/web/guides/migration-to-gis This HTML and JavaScript code demonstrates how to load both the GAPI client and the GIS token client, initialize them, and prepare for API calls. It uses Promises, async/await for managing library loading order and error handling. ```html GAPI and GIS Example

GAPI Client with GIS Authorization

``` -------------------------------- ### Sign In with Presenting View Controller, Hint, and Additional Scopes Source: https://developers.google.com/identity/sign-in/ios/reference/Classes/GIDSignIn.html Initiates the Google sign-in flow with a hint and additional scopes, using a presenting view controller. ```APIDOC ## -signInWithPresentingViewController:hint:additionalScopes:completion: ### Description Initiates the Google sign-in flow with an optional hint and additional OAuth scopes, presenting the sign-in UI modally. ### Method Instance Method ### Endpoint N/A (Instance Method) ### Parameters - **presentingViewController** (UIViewController) - The view controller that will present the sign-in UI. - **hint** (NSString) - An optional hint for the sign-in process (e.g., user's email). - **additionalScopes** (NSArray) - An array of additional OAuth scopes to request. - **completion** (GIDSignInCallback) - A block that is executed upon completion of the sign-in operation. It receives a GIDGoogleUser object and an error if one occurred. ### Response None ``` -------------------------------- ### Start Resolution for Credential Selection Source: https://developers.google.com/identity/smartlock-passwords/android/retrieve-credentials Call this method when a `ResolvableApiException` is caught to start the activity for the user to select a credential. ```Java private void resolveResult(ResolvableApiException rae, int requestCode) { try { rae.startResolutionForResult(MainActivity.this, requestCode); mIsResolving = true; } catch (IntentSender.SendIntentException e) { Log.e(TAG, "Failed to send resolution.", e); hideProgress(); } } ``` -------------------------------- ### 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 ``` -------------------------------- ### OAuth 2.0 Error Response Example Source: https://developers.google.com/identity/protocols/oauth2/web-server This is an example of an error response from the OAuth 2.0 server, indicating that access was denied. ```url https://oauth2.example.com/auth?error=access_denied ``` -------------------------------- ### Example OAuth Error Response Source: https://developers.google.com/identity/oauth2/web/guides/error This is an example of an error response that OAuth may return. Your callback function will receive this response. ```json { "error":"access_denied" } ``` -------------------------------- ### Open Swift Sample Project (Swift Package Manager) Source: https://developers.google.com/identity/sign-in/ios/sample-app Open the DaysUntilBirthday Swift sample project directly in Xcode when using Swift Package Manager. Dependencies will be added automatically. ```bash open GoogleSignIn-iOS/Samples/Swift/DaysUntilBirthday/DaysUntilBirthday.xcodeproj ``` -------------------------------- ### Install Google Authentication 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 ``` -------------------------------- ### GoogleAuth.signIn() Source: https://developers.google.com/identity/sign-in/web/reference Initiates the sign-in process for the user using the options previously configured with `gapi.auth2.init()`. Returns a Promise that resolves with the GoogleUser instance upon successful authentication or rejects with an error. ```APIDOC ## GoogleAuth.signIn() ### Description Initiates the sign-in process for the user using the options previously configured with `gapi.auth2.init()`. Returns a Promise that resolves with the GoogleUser instance upon successful authentication or rejects with an error. ### Returns - **Promise** - A `Promise` that is fulfilled with the `GoogleUser` instance when the user successfully authenticates and grants the requested scopes, or rejected with an object containing an `error` property if an error happened. See `GoogleAuth.signIn(options)` for error codes. ``` -------------------------------- ### Error Response Example Source: https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow An example of an OAuth 2.0 error response, indicating that access was denied. This is returned on the hash fragment of the redirect URI. ```url https://oauth2.example.com/callback#error=access_denied ``` -------------------------------- ### gapi.auth2.authorize Usage Example Source: https://developers.google.com/identity/sign-in/web/reference Demonstrates how to perform a one-time OAuth 2.0 authorization and handle the response, including accessing tokens and using `gapi.client`. ```javascript gapi.auth2.authorize({ client_id: 'CLIENT_ID.apps.googleusercontent.com', scope: 'email profile openid', response_type: 'id_token permission' }, function(response) { if (response.error) { // An error happened! return; } // The user authorized the application for the scopes requested. var accessToken = response.access_token; var idToken = response.id_token; // You can also now use gapi.client to perform authenticated requests. }); ``` -------------------------------- ### Userinfo Endpoint Invalid Token Response Example Source: https://developers.google.com/identity/account-linking/oauth-linking Example of an HTTP 401 Unauthorized response from the userinfo endpoint when the access token is invalid. ```http HTTP/1.1 401 Unauthorized WWW-Authenticate: error="invalid_token", error_description="The Access Token expired" ``` -------------------------------- ### Initialize GIDConfiguration with all properties Source: https://developers.google.com/identity/sign-in/ios/reference/Classes/GIDConfiguration.html Initializes a GIDConfiguration object by specifying all available properties: client ID, server client ID, hosted domain, and OpenID realm. ```Swift init(clientID: String, serverClientID: String?, hostedDomain: String?, openIDRealm: String?) ``` ```Objective-C - (nonnull instancetype)initWithClientID:(nonnull NSString *)clientID serverClientID:(nullable NSString *)serverClientID hostedDomain:(nullable NSString *)hostedDomain openIDRealm:(nullable NSString *)openIDRealm; ```