\n","After the platform library loads, load the ","auth2"," library:","function init() {\n gapi.load('auth2', function() {\n /* Ready. Make a call to gapi.auth2.init or some other API */\n });\n}\n","gapi.auth2.init(","params",")","Initializes the ","GoogleAuth"," object. You must call this method before calling ","gapi.auth2.GoogleAuth","'s methods.","When you initialize the "," object, you configure the object with your OAuth 2.0 client ID and any additional options you want to specify. Then, if the user has already signed in, the "," object restores the user's sign-in state from the previous session.","Arguments","\n An object containing key-value pairs of client configuration data. See\n ","gapi.auth2.ClientConfig"," for the different\n properties configurable. For example:\n ","{\n client_id: 'CLIENT_ID.apps.googleusercontent.com'\n}","Returns","\n The "," object. Use the\n ","then()"," method to get a Promise\n that is resolved when the "," object finishes\n initializing.\n ","GoogleAuth.then(","onInit",", ","onError","Calls the "," function when the "," object is fully\ninitialized. If an error is raised while initializing (this can happen in old unsupported browsers),\nthe "," function will be called instead.","\n The function called with the "," object when it is fully\n initialized.\n ","\n The function called with an object containing an ","error"," property,\n if "," failed to initialize.\n ","Promise","A "," that is fulfilled when the ","\n function has completed, or rejected if an initialization error was raised. It resolves with the\n returned value from the "," function, if any.","Warning:"," do not call ","Promise.resolve()"," and similar with the result of\n ","gapi.auth2.init()",". As the "," object returned implements the\n "," method that resolves with itself, it will create an infinite recursion.\n","Error Codes","idpiframe_initialization_failed","\n Failed to initialize a required iframe from Google, for example, due to an unsupported\n environment. A ","details"," property will give more information on the error raised.\n ","Interface that represents the different configuration parameters for the\n","gapi.auth2.init"," method.","Parameters","client_id","string","\n Required. The app's client ID, found and created in the Google API Console.\n ","cookie_policy","The domains for which to create sign-in cookies. Either a URI,\n ","single_host_origin",", or ","none",". Defaults to\n "," if unspecified.","scope","The scopes to request, as a space-delimited string. Optional if\n ","fetch_basic_profile"," is not set to false.","boolean","Fetch users' basic profile information when they sign in. Adds 'profile', 'email' and\n 'openid' to the requested scopes. True if unspecified.","hosted_domain","The G Suite domain to which users must belong to sign in. This\n is susceptible to modification by clients, so be sure to verify the\n hosted domain property of the returned user. Use\n ","GoogleUser.getHostedDomain()"," on\n the client, and the ","hd"," claim in the ID Token on the\n server to verify the domain is what you expected.\n ","\n You must request the ","'email'"," scope when using this parameter alongside\n ","fetch_basic_profile: false",".\n ","use_fedcm","Optional, defaults to ","True",". Enable or disable the use of\n browser FedCM APIs during sign-in.","ux_mode","The UX mode to use for the sign-in flow. By default, it will open the consent flow\n in a popup. Valid values are ","popup"," and ","redirect",".","redirect_uri","If using ","ux_mode='redirect'",", this parameter lets you override the\n default "," that will be used at the end of the consent flow. The\n default "," is the current URL stripped of query parameters and hash\n fragment.\n ","enable_granular_consent","\n Optional. Whether to enable\n ","granular\n permissions",". If set to ","false",", the more granular Google\n Account permissions will be disabled for OAuth client IDs created before\n 2019. No effect for OAuth Client IDs created during or after 2019, since\n more granular permissions is always enabled for them.\n ","plugin_name","\n Optional. If this value is set, new Client IDs created before July\n 29th, 2022 can use the older Google Platform Library.\n By default, newly created Client IDs are now blocked from using\n the Platform Library and instead must use the newer Google Identity\n Services library. You may choose any value, a descriptive name such as\n product or plugin name is recommended for identification.\n Example: ","plugin_name: 'YOUR_STRING_HERE'","Authentication"," is a singleton class that provides methods to allow the user to sign in with a Google account, get the user's current sign-in status, get specific data from the user's Google profile, request additional scopes, and sign out from the current account.","gapi.auth2.getAuthInstance()","Returns the "," object. You must initialize the "," object with "," before calling this method."," object. Use this object to call\n ","'s methods.\n ","GoogleAuth.isSignedIn.get()","Returns whether the current user is signed in.","Boolean","true"," if the user is signed in, or "," if the\n user is signed out or the "," object isn't\n initialized.\n ","GoogleAuth.isSignedIn.listen(listener)","Listen for changes in the current user's sign-in state.","listener","\n A function that takes a boolean value. ","listen()"," passes\n "," to this function when the user signs in, and\n "," when the user signs out.\n ","GoogleAuth.signIn()","Signs in the user with the options specified to "," that is fulfilled with the ","GoogleUser"," instance when the\n user successfully authenticates and grants the requested scopes, or rejected with an object\n containing an "," property if an error happened. See the\n next section for error codes.","Error codes","See ","GoogleAuth.signIn(","options","Signs in the user using the specified options.","\n Either:\n ","\n A ","gapi.auth2.SignInOptions"," object\n containing key-value pairs of sign-in parameters. For example: ","{\n scope: 'profile email'\n}","An instance of ","gapi.auth2.SigninOptionsBuilder",". For\n example:","\noptions = new gapi.auth2.SigninOptionsBuilder();\noptions.setAppPackageName('com.example.app');\noptions.setFetchBasicProfile(True);\noptions.setPrompt('select_account');\noptions.setScope('profile').setScope('email');"," property if an error happened (see below for error codes).","popup_closed_by_user","\n The user closed the popup before finishing the sign in flow.\n ","access_denied","\n The user denied the permission to the scopes required.\n ","immediate_failed","\n No user could be automatically selected without prompting the consent flow. Error raised when\n using ","signIn"," with ","prompt: 'none'"," option. This option shouldn't be\n required to use, as "," will automatically sign in the user if\n previously signed in during a previous session.\n ","prompt","\n Forces a specific mode for the consent flow. Optional.","\n The possible values are:\n ","consent","\n The authorization server prompts the user for consent before returning\n information to the application.\n ","select_account","\n The authorization server prompts the user to select a Google account. This\n allows a user who has multiple accounts to select amongst the multiple accounts\n that they may have current sessions for.\n "," (","not recommended","\n The authorization server will not display any authentication or user consent\n screens; it will return an error if the user is not already authenticated and\n has not previously consented to the requested scopes.","\n As "," will automatically sign in a user to the\n application if previously signed in, calling\n ","signIn({prompt: 'none'})"," will usually fail.\n ","\n The scopes to request, as a space-delimited string, on top of the scopes defined in the\n "," params. Optional if "," is not set\n to false.\n ",", this parameter lets you override\n the default "," that will be used at the end of the consent\n flow. The default "," is the current URL stripped of query\n parameters and hash fragment.\n ","GoogleAuth.signOut()","Signs out the current account from the application."," that is fulfilled when the user has been signed\n out.","GoogleAuth.disconnect()","Revokes all of the scopes that the user granted.","GoogleAuth.grantOfflineAccess(","Get permission from the user to access the specified scopes offline.","\n A ","gapi.auth2.OfflineAccessOptions","\n object containing key-value pairs of parameters. For example: "," that is fulfilled when the user grants the\n requested scopes, passing an object containing the authorization code to\n the ","'s fulfillment handler.\n For example: ","\nauth2.grantOfflineAccess().then(function(resp) {\n var auth_code = resp.code;\n});","\n The user closed the popup before finishing the consent flow.\n "," option. This option should not be\n required to use, as ","\nmethod.","\n The authorization server prompts the user to select a Google Account. This\n allows a user who has multiple accounts to select amongst the multiple accounts\n that they may have current sessions for.\n ","\n Note that "," is not available for the offline code flow.\n ","GoogleAuth.attachClickHandler(","container","onsuccess","onfailure","Attaches the sign-in flow to the specified container's click handler.","The ID of, or a reference to, the ","div"," element to which to\n attach the click handler.","An object containing key-value pairs of parameters. See\n GoogleAuth.signIn().","The function to call after sign-in completes.","The function to call if sign-in fails.","Users"," object represents one user account.\n"," objects are typically obtained by calling\n","GoogleAuth.currentUser.get()","Returns a "," object\nthat represents the current user. Note that in a newly-initialized\n"," instance, the current user has not been set. Use the\n","currentUser.listen()"," method or the ","GoogleAuth.then()","\nto get an initialized "," instance.","\n The current user\n ","GoogleAuth.currentUser.listen(","Listen for changes in currentUser.","\n A function that takes a "," parameter.\n ","listen"," passes this function a ","\n instance on every change that modifies ","currentUser",".\n ","GoogleUser.getId()","Get the user's unique ID string.","Do not use the Google IDs returned by\n","getId()"," to communicate the signed in user to your backend\nserver. Instead, ","send ID\ntokens",", which can be securely validated on the server.","String","The user's unique ID","GoogleUser.isSignedIn()","Returns true if the user is signed in.","True if the user is signed in","Get the user's G Suite domain if the user signed in with a G Suite account.","The user's G Suite domain","GoogleUser.getGrantedScopes()","Get the scopes that the user granted as a space-delimited string.","The scopes granted by the user","GoogleUser.getBasicProfile()","Get the user's basic profile information.","Do not use the user's profile information to\ncommunicate the signed in user to your backend server. Instead,\nsend ID tokens, which can be\nsecurely validated on the server.","gapi.auth2.BasicProfile","You can retrieve the properties of ","\n with the following methods:\n ","BasicProfile.getId()","BasicProfile.getName()","BasicProfile.getGivenName()","BasicProfile.getFamilyName()","BasicProfile.getImageUrl()","BasicProfile.getEmail()","GoogleUser.getAuthResponse(includeAuthorizationData)","Get the response object from the user's auth session.","includeAuthorizationData","Optional:"," A boolean that specifies whether to always return an access token and\n scopes. By default, the access token and requested scopes are not returned when\n "," is true (the default value) and no additional scopes are\n requested.","gapi.auth2.AuthResponse"," object.","GoogleUser.reloadAuthResponse()","Forces a refresh of the access token, and then returns a Promise for the new AuthResponse."," that is fulfilled with the reloaded\n "," when reloading the\n OAuth token is done.\n ","\n The response returned when calling\n ","GoogleUser.getAuthResponse(","\n oder\n ","\n methods.\n","Properties","access_token","\n The Access Token granted.\n ","id_token","\n The ID Token granted.\n ","\n The scopes granted in the Access Token.\n ","expires_in","number","\n The number of seconds until the Access Token expires.\n ","first_issued_at","\n The timestamp at which the user first granted the scopes requested.\n ","expires_at","\n The timestamp at which the Access Token will expire.\n ","GoogleUser.hasGrantedScopes(","scopes","Returns true if the user granted the specified scopes.","A space-delimited string of scopes.","True if the scopes were granted","GoogleUser.grant(","Request additional scopes to the user."," for the list of\nparameters and the error code.","GoogleUser.grantOfflineAccess(","GoogleUser.disconnect()","Revokes all of the scopes that the user granted for the application.","UI elements","gapi.signin2.render(","id","Renders a sign-in button in the element with the given ID, using\nthe settings specified by the ","The ID of the element in which to render the sign-in button.","\n An object containing the settings to use to render the button. For example:\n ","{\n scope: 'email',\n width: 200,\n height: 50,\n longtitle: true,\n theme: 'dark',\n onsuccess: handleSuccess,\n onfailure: handleFailure\n}","\n You can specify the following options:\n ","The scopes to request when the user signs in (default:\n ","profile",").","width","The width of the button in pixels (default: ","120","height","The height of the button in pixels (default: ","36","longtitle","Display long labels such as \"Sign in with Google\" rather than\n \"Sign in\" (default: ","). When you use long titles,\n you should increase the width of the button from its default.","theme","The color theme of the button: either ","light"," oder\n ","dark"," (default: ","The callback function to call when a user successfully signs in.\n This function must take one argument: an instance of\n ","gapi.auth2.GoogleUser"," (default: none).","The callback function to call when sign-in fails. This function\n takes no arguments (default: none).","Advanced","\n Warning: this section covers features that are not recommended for most use cases. Make\n sure that the methods described in the Guides don't work for your use case before using such\n features.\n","gapi.auth2.authorize(","callback","Performs a one time OAuth 2.0 authorization. Depending on the parameters used, this will open a\npopup to the Google sign-in flow or try to load the requested response silently, without user interaction.","Some use cases where this method is useful include:","Your application only needs to requests a Google API endpoint once, for example to load\nthe user's favorite YouTube videos the first time they sign in.","Your application has its own session management infrastructure, and it only requires the\nID Token once to identify the user in your backend.","Several Client IDs are used within the same page."," do not use this method alongside the recommended\n "," flow.\n These are two distinct behaviors (Authorization for ","gapi.auth2.authorize"," vs\n Authentication for ","gapi.auth2.init/signIn",") and will have unexpected issues if used\n within the same application.\n","\n An object containing key-value pairs of configuration data. See\n ","gapi.auth2.AuthorizeConfig"," for the\n different properties configurable. For example:\n ","{\n client_id: 'CLIENT_ID.apps.googleusercontent.com',\n scope: 'email profile openid',\n response_type: 'id_token permission'\n}","\n A function called with a\n ","gapi.auth2.AuthorizeResponse"," object\n after the request has been completed (either successfully or with a failure).\n ","Example","gapi.auth2.authorize({\n client_id: 'CLIENT_ID.apps.googleusercontent.com',\n scope: 'email profile openid',\n response_type: 'id_token permission'\n}, function(response) {\n if (response.error) {\n // An error happened!\n return;\n }\n // The user authorized the application for the scopes requested.\n var accessToken = response.access_token;\n var idToken = response.id_token;\n // You can also now use gapi.client to perform authenticated requests.\n});\n","\n Failed to initialize a required iframe from Google, for instance, due to an unsupported\n environment. A "," option.\n ","\n Required. The app's client ID, found and created in the Google API Console.\n ","Required. The scopes to request, as a space-delimited string.","response_type","\n A list of space-delimited response type. Defaults to ","'permission'",". The possible\n values are:\n ",", to retrieve an ID Token","permission"," (or ","token","), to retrieve an Access Token","code",", to retrieve an Authorization Code","\n Forces a specific mode for the consent flow. The possible values are:\n ","\n If "," is requested as response type, the code returned will only be\n exchangeable for an ",", not a ","refresh_token",".\n ","Note :"," under the hood, the library caches and automatically refreshes the last\n Access Token obtained. When using ",", most of the time, no HTTP\n request to the backend will be necessary to obtain a valid token.\n ","\n The domains for which to create sign-in cookies. Either a URI,\n ",". Defaults to\n "," if unspecified.\n ","\n The G Suite domain to which users must belong to sign in. This is susceptible to modification\n by clients, so be sure to verify the hosted domain property of the returned user.\n ","login_hint","\n The email, or User ID, of a user to pre-select in the sign-in flow. This is susceptible to\n modification by the user, unless ","prompt: \"none\""," is used.\n ","include_granted_scopes","\n Whether to request an Access Token that includes all the scopes previously granted by the user\n to the app, or only the scopes requested in the current call. Defaults to ","\n Optional. Whether to enable\n ","granular\n permissions",", the more granular Google\n Account permissions will be disabled for OAuth client IDs created before\n 2019. No effect for OAuth Client IDs created during or after 2019, since\n more granular permissions is always enabled for them.\n ","\n Optional. If set, Client IDs created before July 29th, 2022 can use the\n Google Platform Library. By default, newly created Client IDs are blocked\n from using the Platform Library and instead must use the newer Google\n Identity Services library. You may choose any value, a descriptive name\n such as product or plugin name is recommended for easy identification.\n Example: ","The response returned to the callback of the\n","\n The Access Token granted. Only present if "," oder "," was\n specified in the ","\n The ID Token granted. Only present if "," was specified in the\n ","\n The Authorization Code granted. Only present if ","\n The scopes granted in the Access Token. Only present if "," oder\n "," was specified in the ","\n The number of seconds until the Access Token expires. Only present if ","\n oder ","\n The timestamp at which the user first granted the scopes requested. Only present if\n ","\n The timestamp at which the Access Token will expire. Only present if ","\n When the request failed, this contains the\n error code.\n ","error_subtype","\n When the request failed, this can contain additional information to the error code also\n returned.\n ","Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.","Last updated 2024-07-10 UTC.","\n [{\n \"type\": \"thumb-down\",\n \"id\": \"missingTheInformationINeed\",\n \"label\":\"Missing the information I need\"\n },{\n \"type\": \"thumb-down\",\n \"id\": \"tooComplicatedTooManySteps\",\n \"label\":\"Too complicated / too many steps\"\n },{\n \"type\": \"thumb-down\",\n \"id\": \"outOfDate\",\n \"label\":\"Out of date\"\n },{\n \"type\": \"thumb-down\",\n \"id\": \"samplesCodeIssue\",\n \"label\":\"Samples / code issue\"\n },{\n \"type\": \"thumb-down\",\n \"id\": \"otherDown\",\n \"label\":\"Other\"\n }]\n ","\n [{\n \"type\": \"thumb-up\",\n \"id\": \"easyToUnderstand\",\n \"label\":\"Easy to understand\"\n },{\n \"type\": \"thumb-up\",\n \"id\": \"solvedMyProblem\",\n \"label\":\"Solved my problem\"\n },{\n \"type\": \"thumb-up\",\n \"id\": \"otherUp\",\n \"label\":\"Other\"\n }]\n ","\n \n Need to tell us more?\n \n ","\n GitHub\n ","Fork our samples and try them yourself","\n Stack Overflow\n ","Ask a question under the google-signin tag","\n Blog\n ","The latest news on the Google Developers blog","\n Chromium Blog\n ","The latest news on the Chromium blog.","Product Info","\n \n \n Terms of Service\n \n ","\n \n \n \n \n \n Branding Guidelines\n \n ","Help","\n \n \n Sign In With Google\n \n ","\n \n \n \n \n \n Google Identity\n \n ","Developer consoles","\n \n \n Google API Console\n \n ","\n \n \n Google Cloud Platform Console\n \n ","\n \n \n Google Play Console\n \n ","\n \n \n Firebase Console\n \n ","\n \n \n Actions on Google Console\n \n ","\n \n \n Cast SDK Developer Console\n \n ","\n \n \n \n \n \n Chrome Web Store Dashboard\n \n ","\n Android\n ","\n Chrome\n ","\n Firebase\n ","\n Google Cloud Platform\n ","\n All products\n ","\n Terms\n ","\n Privacy\n ","\n Manage cookies\n ","\n \n Sign up for the Google for Developers newsletter\n \n \n \n Subscribe\n \n \n "]}
After the platform library loads, load the auth2 library:
function init() {
gapi.load('auth2', function() {
/* Ready. Make a call to gapi.auth2.init or some other API */
});
}
gapi.auth2.init(params)
Initializes the GoogleAuth object. You must call this method before calling gapi.auth2.GoogleAuth's methods.
When you initialize the GoogleAuth object, you configure the object with your OAuth 2.0 client ID and any additional options you want to specify. Then, if the user has already signed in, the GoogleAuth object restores the user's sign-in state from the previous session.
Arguments
params
An object containing key-value pairs of client configuration data. See
gapi.auth2.ClientConfig for the different
properties configurable. For example:
The gapi.auth2.GoogleAuth object. Use the
then() method to get a Promise
that is resolved when the gapi.auth2.GoogleAuth object finishes
initializing.
GoogleAuth.then(onInit, onError)
Calls the onInit function when the GoogleAuth object is fully
initialized. If an error is raised while initializing (this can happen in old unsupported browsers),
the onError function will be called instead.
Arguments
onInit
The function called with the GoogleAuth object when it is fully
initialized.
onError
The function called with an object containing an error property,
if GoogleAuth failed to initialize.
Returns
Promise
A Promise that is fulfilled when the onInit
function has completed, or rejected if an initialization error was raised. It resolves with the
returned value from the onInit function, if any.
Error Codes
idpiframe_initialization_failed
Failed to initialize a required iframe from Google, for example, due to an unsupported
environment. A details property will give more information on the error raised.
gapi.auth2.ClientConfig
Interface that represents the different configuration parameters for the
gapi.auth2.init method.
Parameters
client_id
string
Required. The app's client ID, found and created in the Google API Console.
cookie_policy
string
The domains for which to create sign-in cookies. Either a URI,
single_host_origin, or none. Defaults to
single_host_origin if unspecified.
scope
string
The scopes to request, as a space-delimited string. Optional if
fetch_basic_profile is not set to false.
fetch_basic_profile
boolean
Fetch users' basic profile information when they sign in. Adds 'profile', 'email' and
'openid' to the requested scopes. True if unspecified.
hosted_domain
string
The G Suite domain to which users must belong to sign in. This
is susceptible to modification by clients, so be sure to verify the
hosted domain property of the returned user. Use
GoogleUser.getHostedDomain() on
the client, and the hd claim in the ID Token on the
server to verify the domain is what you expected.
use_fedcm
boolean
Optional, defaults to True. Enable or disable the use of
browser FedCM APIs during sign-in.
ux_mode
string
The UX mode to use for the sign-in flow. By default, it will open the consent flow
in a popup. Valid values are popup and redirect.
redirect_uri
string
If using ux_mode='redirect', this parameter lets you override the
default redirect_uri that will be used at the end of the consent flow. The
default redirect_uri is the current URL stripped of query parameters and hash
fragment.
enable_granular_consent
boolean
Optional. Whether to enable
granular
permissions. If set to false, the more granular Google
Account permissions will be disabled for OAuth client IDs created before
2019. No effect for OAuth Client IDs created during or after 2019, since
more granular permissions is always enabled for them.
plugin_name
string
Optional. If this value is set, new Client IDs created before July
29th, 2022 can use the older Google Platform Library.
By default, newly created Client IDs are now blocked from using
the Platform Library and instead must use the newer Google Identity
Services library. You may choose any value, a descriptive name such as
product or plugin name is recommended for identification.
Example: plugin_name: 'YOUR_STRING_HERE'
Authentication
GoogleAuth is a singleton class that provides methods to allow the user to sign in with a Google account, get the user's current sign-in status, get specific data from the user's Google profile, request additional scopes, and sign out from the current account.
gapi.auth2.getAuthInstance()
Returns the GoogleAuth object. You must initialize the GoogleAuth object with gapi.auth2.init() before calling this method.
Returns
gapi.auth2.GoogleAuth
The gapi.auth2.GoogleAuth object. Use this object to call
gapi.auth2.GoogleAuth's methods.
GoogleAuth.isSignedIn.get()
Returns whether the current user is signed in.
Returns
Boolean
true if the user is signed in, or false if the
user is signed out or the GoogleAuth object isn't
initialized.
GoogleAuth.isSignedIn.listen(listener)
Listen for changes in the current user's sign-in state.
Arguments
listener
A function that takes a boolean value. listen() passes
true to this function when the user signs in, and
false when the user signs out.
GoogleAuth.signIn()
Signs in the user with the options specified to gapi.auth2.init().
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 the
next section for error codes.
A gapi.auth2.SignInOptions object
containing key-value pairs of sign-in parameters. For example:
{
scope: 'profile email'
}
An instance of gapi.auth2.SigninOptionsBuilder. For
example:
options = new gapi.auth2.SigninOptionsBuilder();
options.setAppPackageName('com.example.app');
options.setFetchBasicProfile(True);
options.setPrompt('select_account');
options.setScope('profile').setScope('email');
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 below for error codes).
Error codes
popup_closed_by_user
The user closed the popup before finishing the sign in flow.
access_denied
The user denied the permission to the scopes required.
immediate_failed
No user could be automatically selected without prompting the consent flow. Error raised when
using signIn with prompt: 'none' option. This option shouldn't be
required to use, as gapi.auth2.init will automatically sign in the user if
previously signed in during a previous session.
gapi.auth2.SignInOptions
Interface that represents the different configuration parameters for the
GoogleAuth.signIn(options) method.
Parameters
prompt
string
Forces a specific mode for the consent flow. Optional.
The possible values are:
consent
The authorization server prompts the user for consent before returning
information to the application.
select_account
The authorization server prompts the user to select a Google account. This
allows a user who has multiple accounts to select amongst the multiple accounts
that they may have current sessions for.
none (not recommended)
The authorization server will not display any authentication or user consent
screens; it will return an error if the user is not already authenticated and
has not previously consented to the requested scopes.
As gapi.auth2.init will automatically sign in a user to the
application if previously signed in, calling
signIn({prompt: 'none'}) will usually fail.
scope
string
The scopes to request, as a space-delimited string, on top of the scopes defined in the
gapi.auth2.init params. Optional if fetch_basic_profile is not set
to false.
ux_mode
string
The UX mode to use for the sign-in flow. By default, it will open the consent flow
in a popup. Valid values are popup and redirect.
redirect_uri
string
If using ux_mode='redirect', this parameter lets you override
the default redirect_uri that will be used at the end of the consent
flow. The default redirect_uri is the current URL stripped of query
parameters and hash fragment.
GoogleAuth.signOut()
Signs out the current account from the application.
Returns
Promise
A Promise that is fulfilled when the user has been signed
out.
GoogleAuth.disconnect()
Revokes all of the scopes that the user granted.
GoogleAuth.grantOfflineAccess(options)
Get permission from the user to access the specified scopes offline.
A Promise that is fulfilled when the user grants the
requested scopes, passing an object containing the authorization code to
the Promise's fulfillment handler.
For example:
auth2.grantOfflineAccess().then(function(resp) {
var auth_code = resp.code;
});
Error codes
popup_closed_by_user
The user closed the popup before finishing the consent flow.
access_denied
The user denied the permission to the scopes required.
immediate_failed
No user could be automatically selected without prompting the consent flow. Error raised when
using signIn with prompt: 'none' option. This option should not be
required to use, as gapi.auth2.init will automatically sign in the user if
previously signed in during a previous session.
Forces a specific mode for the consent flow. Optional.
The possible values are:
consent
The authorization server prompts the user for consent before returning
information to the application.
select_account
The authorization server prompts the user to select a Google Account. This
allows a user who has multiple accounts to select amongst the multiple accounts
that they may have current sessions for.
scope
string
The scopes to request, as a space-delimited string, on top of the scopes defined in the
gapi.auth2.init params. Optional if fetch_basic_profile is not set
to false.
Attaches the sign-in flow to the specified container's click handler.
Arguments
container
The ID of, or a reference to, the div element to which to
attach the click handler.
options
An object containing key-value pairs of parameters. See
GoogleAuth.signIn().
onsuccess
The function to call after sign-in completes.
onfailure
The function to call if sign-in fails.
Users
A GoogleUser object represents one user account.
GoogleUser objects are typically obtained by calling
GoogleAuth.currentUser.get().
GoogleAuth.currentUser.get()
Returns a GoogleUser object
that represents the current user. Note that in a newly-initialized
GoogleAuth instance, the current user has not been set. Use the
currentUser.listen() method or the GoogleAuth.then()
to get an initialized GoogleAuth instance.
Returns
GoogleUser
The current user
GoogleAuth.currentUser.listen(listener)
Listen for changes in currentUser.
Arguments
listener
A function that takes a GoogleUser parameter.
listen passes this function a GoogleUser
instance on every change that modifies currentUser.
GoogleUser.getId()
Get the user's unique ID string.
Returns
String
The user's unique ID
GoogleUser.isSignedIn()
Returns true if the user is signed in.
Returns
Boolean
True if the user is signed in
GoogleUser.getHostedDomain()
Get the user's G Suite domain if the user signed in with a G Suite account.
Returns
String
The user's G Suite domain
GoogleUser.getGrantedScopes()
Get the scopes that the user granted as a space-delimited string.
Returns
String
The scopes granted by the user
GoogleUser.getBasicProfile()
Get the user's basic profile information.
Returns
gapi.auth2.BasicProfile
You can retrieve the properties of gapi.auth2.BasicProfile
with the following methods:
Get the response object from the user's auth session.
Arguments
includeAuthorizationData
Optional: A boolean that specifies whether to always return an access token and
scopes. By default, the access token and requested scopes are not returned when
fetch_basic_profile is true (the default value) and no additional scopes are
requested.
The scopes to request when the user signs in (default:
profile).
width
The width of the button in pixels (default: 120).
height
The height of the button in pixels (default: 36).
longtitle
Display long labels such as "Sign in with Google" rather than
"Sign in" (default: false). When you use long titles,
you should increase the width of the button from its default.
theme
The color theme of the button: either light oder
dark (default: light).
onsuccess
The callback function to call when a user successfully signs in.
This function must take one argument: an instance of
gapi.auth2.GoogleUser (default: none).
onfailure
The callback function to call when sign-in fails. This function
takes no arguments (default: none).
Advanced
gapi.auth2.authorize(params, callback)
Performs a one time OAuth 2.0 authorization. Depending on the parameters used, this will open a
popup to the Google sign-in flow or try to load the requested response silently, without user interaction.
Some use cases where this method is useful include:
Your application only needs to requests a Google API endpoint once, for example to load
the user's favorite YouTube videos the first time they sign in.
Your application has its own session management infrastructure, and it only requires the
ID Token once to identify the user in your backend.
Several Client IDs are used within the same page.
Arguments
params
An object containing key-value pairs of configuration data. See
gapi.auth2.AuthorizeConfig for the
different properties configurable. For example:
A function called with a
gapi.auth2.AuthorizeResponse object
after the request has been completed (either successfully or with a failure).
Example
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.
});
Error codes
idpiframe_initialization_failed
Failed to initialize a required iframe from Google, for instance, due to an unsupported
environment. A details property will give more information on the error raised.
popup_closed_by_user
The user closed the popup before finishing the sign in flow.
access_denied
The user denied the permission to the scopes required.
immediate_failed
No user could be automatically selected without prompting the consent flow. Error raised when
using signIn with prompt: 'none' option.
gapi.auth2.AuthorizeConfig
Interface that represents the different configuration parameters for the
gapi.auth2.authorize method.
Properties
client_id
string
Required. The app's client ID, found and created in the Google API Console.
scope
string
Required. The scopes to request, as a space-delimited string.
response_type
string
A list of space-delimited response type. Defaults to 'permission'. The possible
values are:
id_token, to retrieve an ID Token
permission (or token), to retrieve an Access Token
code, to retrieve an Authorization Code
prompt
string
Forces a specific mode for the consent flow. The possible values are:
consent
The authorization server prompts the user for consent before returning
information to the application.
select_account
The authorization server prompts the user to select a Google account. This
allows a user who has multiple accounts to select amongst the multiple accounts
that they may have current sessions for.
none
The authorization server will not display any authentication or user consent
screens; it will return an error if the user is not already authenticated and
has not previously consented to the requested scopes.
If code is requested as response type, the code returned will only be
exchangeable for an access_token, not a refresh_token.
cookie_policy
string
The domains for which to create sign-in cookies. Either a URI,
single_host_origin, or none. Defaults to
single_host_origin if unspecified.
hosted_domain
string
The G Suite domain to which users must belong to sign in. This is susceptible to modification
by clients, so be sure to verify the hosted domain property of the returned user.
login_hint
string
The email, or User ID, of a user to pre-select in the sign-in flow. This is susceptible to
modification by the user, unless prompt: "none" is used.
include_granted_scopes
boolean
Whether to request an Access Token that includes all the scopes previously granted by the user
to the app, or only the scopes requested in the current call. Defaults to true.
enable_granular_consent
boolean
Optional. Whether to enable
granular
permissions. If set to false, the more granular Google
Account permissions will be disabled for OAuth client IDs created before
2019. No effect for OAuth Client IDs created during or after 2019, since
more granular permissions is always enabled for them.
plugin_name
string
Optional. If set, Client IDs created before July 29th, 2022 can use the
Google Platform Library. By default, newly created Client IDs are blocked
from using the Platform Library and instead must use the newer Google
Identity Services library. You may choose any value, a descriptive name
such as product or plugin name is recommended for easy identification.
Example: plugin_name: 'YOUR_STRING_HERE'