Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Con el procedimiento anterior de Agregar acceso, tu app autentica al usuario solo del lado del cliente. En ese caso, solo puedes acceder a las APIs de Google mientras el usuario usa activamente tu app. Si deseas que tus servidores puedan realizar llamadas a la API de Google en nombre de los usuarios, posiblemente mientras estén sin conexión, tu servidor requiere un token de acceso.
Crea un ID de cliente de aplicación web de OAuth 2.0 para tu servidor de backend. Este ID de cliente es diferente del ID de cliente de tu app. Puedes buscar o crear un ID de cliente para tu servidor en la Consola de API de Google.
Habilita el acceso a la API del servidor para tu app
Cuando configures el Acceso con Google, compila el objeto GoogleSignInOptions con el método requestServerAuthCode y especifica los permisos a los que el backend de tu app debe acceder con el método [requestScopes][55].
Pasa el ID de cliente de tu servidor al método requestServerAuthCode.
// Configure sign-in to request offline access to the user's ID, basic// profile, and Google Drive. The first time you request a code you will// be able to exchange it for an access token and refresh token, which// you should store. In subsequent calls, the code will only result in// an access token. By asking for profile access (through// DEFAULT_SIGN_IN) you will also get an ID Token as a result of the// code exchange.StringserverClientId=getString(R.string.server_client_id);GoogleSignInOptionsgso=newGoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestScopes(newScope(Scopes.DRIVE_APPFOLDER)).requestServerAuthCode(serverClientId).requestEmail().build();
En el servidor de backend de tu app, intercambia el código de Auth por tokens de acceso y actualización. Usa el token de acceso para llamar a las APIs de Google en nombre del usuario y, de manera opcional, almacena el token de actualización para adquirir un token de acceso nuevo cuando este venza.
Si solicitaste acceso al perfil, también obtendrás un token de ID que contiene información básica del perfil del usuario.
Por ejemplo:
Java
// (Receive authCode via HTTPS POST)if(request.getHeader("X-Requested-With")==null){// Without the `X-Requested-With` header, this request could be forged. Aborts.}// Set path to the Web application client_secret_*.json file you downloaded from the// Google API Console: https://console.cloud.google.com/apis/credentials// You can also find your Web application client ID and client secret from the// console and specify them directly when you create the GoogleAuthorizationCodeTokenRequest// object.StringCLIENT_SECRET_FILE="/path/to/client_secret.json";// Exchange auth code for access tokenGoogleClientSecretsclientSecrets=GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(),newFileReader(CLIENT_SECRET_FILE));GoogleTokenResponsetokenResponse=newGoogleAuthorizationCodeTokenRequest(newNetHttpTransport(),JacksonFactory.getDefaultInstance(),"https://oauth2.googleapis.com/token",clientSecrets.getDetails().getClientId(),clientSecrets.getDetails().getClientSecret(),authCode,REDIRECT_URI)// Specify the same redirect URI that you use with your web// app. If you don't have a web version of your app, you can// specify an empty string..execute();StringaccessToken=tokenResponse.getAccessToken();// Use access token to call APIGoogleCredentialcredential=newGoogleCredential().setAccessToken(accessToken);Drivedrive=newDrive.Builder(newNetHttpTransport(),JacksonFactory.getDefaultInstance(),credential).setApplicationName("Auth Code Exchange Demo").build();Filefile=drive.files().get("appfolder").execute();// Get profile info from ID tokenGoogleIdTokenidToken=tokenResponse.parseIdToken();GoogleIdToken.Payloadpayload=idToken.getPayload();StringuserId=payload.getSubject();// Use this value as a key to identify a user.Stringemail=payload.getEmail();booleanemailVerified=Boolean.valueOf(payload.getEmailVerified());Stringname=(String)payload.get("name");StringpictureUrl=(String)payload.get("picture");Stringlocale=(String)payload.get("locale");StringfamilyName=(String)payload.get("family_name");StringgivenName=(String)payload.get("given_name");
Python
fromapiclientimportdiscoveryimporthttplib2fromoauth2clientimportclient# (Receive auth_code by HTTPS POST)# If this request does not have `X-Requested-With` header, this could be a CSRFifnotrequest.headers.get('X-Requested-With'):abort(403)# Set path to the Web application client_secret_*.json file you downloaded from the# Google API Console: https://console.cloud.google.com/apis/credentialsCLIENT_SECRET_FILE='/path/to/client_secret.json'# Exchange auth code for access token, refresh token, and ID tokencredentials=client.credentials_from_clientsecrets_and_code(CLIENT_SECRET_FILE,['https://www.googleapis.com/auth/drive.appdata','profile','email'],auth_code)# Call Google APIhttp_auth=credentials.authorize(httplib2.Http())drive_service=discovery.build('drive','v3',http=http_auth)appfolder=drive_service.files().get(fileId='appfolder').execute()# Get profile info from ID tokenuserid=credentials.id_token['sub']email=credentials.id_token['email']
El contenido y las muestras de código que aparecen en esta página están sujetas a las licencias que se describen en la Licencia de Contenido. Java y OpenJDK son marcas registradas de Oracle o sus afiliados.
Última actualización: 2025-07-27 (UTC)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-07-27 (UTC)"],[],[],null,["# Enabling Server-Side Access\n\n| **Warning:**\n|\n| **The Google Sign-In for Android API is outdated and no longer supported.**\n| To ensure the continued security and usability of your app, [migrate your Sign in with\n| Google implementation to Credential Manager](/identity/sign-in/credential-manager-siwg) today. Credential Manager\n| supports passkey, password, and federated identity authentication (such as\n| Sign-in with Google), stronger security, and a more consistent user\n| experience.\n|\n| **For Wear developers:** Credential Manager will be supported in Wear OS\n| 5.1 and later on selected watches. Developers actively supporting Wear OS 3, 4\n| and 5.0 devices with Sign in with Google should continue using Google Sign-in\n| for Android for your Wear applications. Sign in with Google support will be\n| available on Credential Manager APIs for these versions of WearOS at a later\n| date.\n\nWith the earlier [Add Sign-In](/identity/legacy/gsi/legacy-sign-in#add_the_google_sign-in_button_to_your_app)\nprocedure, your app authenticates the user on the client side only; in that case,\nyou can access the Google APIs only while the user is actively using your app.\nIf you want your servers to be able to make Google API calls on behalf of\nusers---possibly while they are offline---your server requires an access\ntoken.\n\nBefore you begin\n----------------\n\n- Configure a project in Android Studio\n- [Add a Google Sign-In button to your app](/identity/legacy/gsi/legacy-sign-in)\n- Create an OAuth 2.0 web application client ID for your backend server. This client ID is different from your app's client ID. You can find or create a client ID for your server in the [Google API Console](https://console.cloud.google.com/apis/credentials).\n\nEnable server-side API access for your app\n------------------------------------------\n\n1. When you [configure Google Sign-In](/identity/legacy/gsi/legacy-sign-in#configure_google_sign-in_and_the_googlesigninclient_object),\n build the `GoogleSignInOptions` object with the [`requestServerAuthCode`](https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInOptions.Builder.html#requestServerAuthCode(java.lang.String))\n method and specify the scopes that your app's backend needs to access with\n the \\[`requestScopes`\\]\\[55\\]\n method.\n\n Pass your server's client ID to the `requestServerAuthCode` method. \n\n ```scilab\n // Configure sign-in to request offline access to the user's ID, basic\n // profile, and Google Drive. The first time you request a code you will\n // be able to exchange it for an access token and refresh token, which\n // you should store. In subsequent calls, the code will only result in\n // an access token. By asking for profile access (through\n // DEFAULT_SIGN_IN) you will also get an ID Token as a result of the\n // code exchange.\n String serverClientId = getString(R.string.server_client_id);\n GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)\n .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))\n .requestServerAuthCode(serverClientId)\n .requestEmail()\n .build();\n ```\n2. After the user [successfully signs in](/identity/legacy/gsi/legacy-sign-in#start_the_sign-in_flow),\n get an auth code for the user with [`getServerAuthCode`](https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount.html#getServerAuthCode()):\n\n ```text\n Task\u003cGoogleSignInAccount\u003e task = GoogleSignIn.getSignedInAccountFromIntent(data);\n try {\n GoogleSignInAccount account = task.getResult(ApiException.class);\n String authCode = account.getServerAuthCode();\n\n // Show signed-un UI\n updateUI(account);\n\n // TODO(developer): send code to server and exchange for access/refresh/ID tokens\n } catch (ApiException e) {\n Log.w(TAG, \"Sign-in failed\", e);\n updateUI(null);\n }\n ```\n3. Send the auth code to your app's backend using HTTPS POST:\n\n HttpPost httpPost = new HttpPost(\"https://yourbackend.example.com/authcode\");\n\n try {\n List\u003cNameValuePair\u003e nameValuePairs = new ArrayList\u003cNameValuePair\u003e(1);\n nameValuePairs.add(new BasicNameValuePair(\"authCode\", authCode));\n httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));\n\n HttpResponse response = httpClient.execute(httpPost);\n int statusCode = response.getStatusLine().getStatusCode();\n final String responseBody = EntityUtils.toString(response.getEntity());\n } catch (ClientProtocolException e) {\n Log.e(TAG, \"Error sending auth code to backend.\", e);\n } catch (IOException e) {\n Log.e(TAG, \"Error sending auth code to backend.\", e);\n }\n\n4. On your app's backend server, exchange the auth code for access and refresh\n tokens. Use the access token to call Google APIs on behalf of the user and,\n optionally, store the refresh token to acquire a new access token when the\n access token expires.\n\n If you requested profile access, you also get an ID token that contains\n basic profile information for the user.\n\n For example: \n\n ##### Java\n\n ```java\n // (Receive authCode via HTTPS POST)\n\n if (request.getHeader(\"X-Requested-With\") == null) {\n // Without the `X-Requested-With` header, this request could be forged. Aborts.\n }\n\n // Set path to the Web application client_secret_*.json file you downloaded from the\n // Google API Console: https://console.cloud.google.com/apis/credentials\n // You can also find your Web application client ID and client secret from the\n // console and specify them directly when you create the GoogleAuthorizationCodeTokenRequest\n // object.\n String CLIENT_SECRET_FILE = \"/path/to/client_secret.json\";\n\n // Exchange auth code for access token\n GoogleClientSecrets clientSecrets =\n GoogleClientSecrets.load(\n JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));\n GoogleTokenResponse tokenResponse =\n new GoogleAuthorizationCodeTokenRequest(\n new NetHttpTransport(),\n JacksonFactory.getDefaultInstance(),\n \"https://oauth2.googleapis.com/token\",\n clientSecrets.getDetails().getClientId(),\n clientSecrets.getDetails().getClientSecret(),\n authCode,\n REDIRECT_URI) // Specify the same redirect URI that you use with your web\n // app. If you don't have a web version of your app, you can\n // specify an empty string.\n .execute();\n\n String accessToken = tokenResponse.getAccessToken();\n\n // Use access token to call API\n GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);\n Drive drive =\n new Drive.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential)\n .setApplicationName(\"Auth Code Exchange Demo\")\n .build();\n File file = drive.files().get(\"appfolder\").execute();\n\n // Get profile info from ID token\n GoogleIdToken idToken = tokenResponse.parseIdToken();\n GoogleIdToken.Payload payload = idToken.getPayload();\n String userId = payload.getSubject(); // Use this value as a key to identify a user.\n String email = payload.getEmail();\n boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());\n String name = (String) payload.get(\"name\");\n String pictureUrl = (String) payload.get(\"picture\");\n String locale = (String) payload.get(\"locale\");\n String familyName = (String) payload.get(\"family_name\");\n String givenName = (String) payload.get(\"given_name\");\n ```\n\n ##### Python\n\n ```python\n from apiclient import discovery\n import httplib2\n from oauth2client import client\n\n # (Receive auth_code by HTTPS POST)\n\n # If this request does not have `X-Requested-With` header, this could be a CSRF\n if not request.headers.get('X-Requested-With'):\n abort(403)\n\n # Set path to the Web application client_secret_*.json file you downloaded from the\n # Google API Console: https://console.cloud.google.com/apis/credentials\n CLIENT_SECRET_FILE = '/path/to/client_secret.json'\n\n # Exchange auth code for access token, refresh token, and ID token\n credentials = client.credentials_from_clientsecrets_and_code(\n CLIENT_SECRET_FILE,\n ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],\n auth_code)\n\n # Call Google API\n http_auth = credentials.authorize(httplib2.Http())\n drive_service = discovery.build('drive', 'v3', http=http_auth)\n appfolder = drive_service.files().get(fileId='appfolder').execute()\n\n # Get profile info from ID token\n userid = credentials.id_token['sub']\n email = credentials.id_token['email']\n ```\n\n\\[55\\]: https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInOptions.Builder.html#requestScopes(com.google.android.gms.common.api.Scope, com.google.android.gms.common.api.Scope...)"]]