Zadbaj o dobrą organizację dzięki kolekcji
Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.
W ramach wcześniejszej procedury Dodaj logowanie aplikacja uwierzytelnia użytkownika tylko po stronie klienta. W takim przypadku możesz uzyskać dostęp do interfejsów Google API tylko wtedy, gdy użytkownik aktywnie korzysta z aplikacji. Jeśli chcesz, aby Twoje serwery mogły wywoływać interfejsy Google API w imieniu użytkowników (np. gdy są offline), serwer musi mieć token dostępu.
Utwórz identyfikator klienta aplikacji internetowej OAuth 2.0 dla serwera zaplecza. Ten identyfikator klienta różni się od identyfikatora klienta Twojej aplikacji. Identyfikator klienta dla serwera możesz znaleźć lub utworzyć w Konsoli interfejsów API Google.
Włączanie w aplikacji dostępu do interfejsu API po stronie serwera
Podczas konfigurowania logowania z Google utwórz obiekt GoogleSignInOptions za pomocą metody requestServerAuthCode i określ zakresy, do których backend aplikacji musi mieć dostęp za pomocą metody [requestScopes][55].
Przekaż identyfikator klienta serwera do metody 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();
Na serwerze backendu aplikacji zastąp kod uwierzytelniający tokenami dostępu i odświeżania. Używaj tokena dostępu do wywoływania interfejsów API Google w imieniu użytkownika. Opcjonalnie możesz też przechowywać token odświeżania, aby po wygaśnięciu tokena dostępu pobrać nowy.
Jeśli poprosisz o dostęp do profilu, otrzymasz też token identyfikacyjny zawierający podstawowe informacje o profilu użytkownika.
Przykład:
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']
Treść strony i umieszczone na niej fragmenty kodu podlegają licencjom opisanym w Licencji na treści. Java i OpenJDK są znakami towarowymi lub zastrzeżonymi znakami towarowymi należącymi do firmy Oracle lub jej podmiotów stowarzyszonych.
Ostatnia aktualizacja: 2025-07-27 UTC.
[[["Łatwo zrozumieć","easyToUnderstand","thumb-up"],["Rozwiązało to mój problem","solvedMyProblem","thumb-up"],["Inne","otherUp","thumb-up"]],[["Brak potrzebnych mi informacji","missingTheInformationINeed","thumb-down"],["Zbyt skomplikowane / zbyt wiele czynności do wykonania","tooComplicatedTooManySteps","thumb-down"],["Nieaktualne treści","outOfDate","thumb-down"],["Problem z tłumaczeniem","translationIssue","thumb-down"],["Problem z przykładami/kodem","samplesCodeIssue","thumb-down"],["Inne","otherDown","thumb-down"]],["Ostatnia aktualizacja: 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...)"]]