이전의 로그인 추가 절차를 사용하면 앱이 클라이언트 측에서만 사용자를 인증합니다. 이 경우 사용자가 앱을 사용 중일 때만 Google API에 액세스할 수 있습니다. 서버가 사용자가 오프라인 상태일 때도 사용자를 대신하여 Google API를 호출할 수 있도록 하려면 서버에 액세스 토큰이 필요합니다.
// 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();
앱의 백엔드 서버에서 인증 코드를 액세스 토큰 및 갱신 토큰으로 교환합니다. 액세스 토큰을 사용하여 사용자를 대신해 Google API를 호출합니다. 선택적으로 갱신 토큰을 저장하여 액세스 토큰이 만료되면 새 액세스 토큰을 획득할 수 있습니다.
프로필 액세스를 요청한 경우 사용자의 기본 프로필 정보가 포함된 ID 토큰도 가져옵니다.
예를 들면 다음과 같습니다.
자바
// (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']
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 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...)"]]