สำคัญ: ตั้งแต่วันที่
1 พฤษภาคม 2024 เป็นต้นไป Apple จะ
กำหนดให้ใช้ไฟล์ Manifest ด้านความเป็นส่วนตัวและลายเซ็นสำหรับแอปพลิเคชัน iOS ที่ใช้ SDK ที่ใช้กันโดยทั่วไป ซึ่งรวมถึง GoogleSignIn-iOS อัปเกรดเป็น GoogleSignIn-iOS v7.1.0 ขึ้นไปก่อนวันที่ 1 พฤษภาคม 2024 ทำตาม
คู่มือการอัปเกรด
เข้าถึง Google APIs จากแบ็กเอนด์ของแอป
จัดทุกอย่างให้เป็นระเบียบอยู่เสมอด้วยคอลเล็กชัน
บันทึกและจัดหมวดหมู่เนื้อหาตามค่ากำหนดของคุณ
โปรดทำตามขั้นตอนนี้หากต้องการให้เซิร์ฟเวอร์ดำเนินการต่อไปนี้ได้
การเรียก Google API ในนามของผู้ใช้หรือในขณะที่ผู้ใช้ออฟไลน์
ก่อนเริ่มต้น
คุณต้องดำเนินการผสานรวม Google Sign-In พื้นฐานให้เสร็จสมบูรณ์
เปิดใช้การเข้าถึง API ฝั่งเซิร์ฟเวอร์สำหรับแอป
ในหน้าเข้าถึง Google API ในแอป iOS
แอปของคุณจะตรวจสอบสิทธิ์ผู้ใช้ในฝั่งไคลเอ็นต์เท่านั้น ในกรณีนี้
แอปของคุณจะเข้าถึง Google APIs ได้เฉพาะเมื่อผู้ใช้กำลังใช้งานเท่านั้น
แอปของคุณ
ด้วยกระบวนการที่อธิบายในหน้านี้ เซิร์ฟเวอร์ของคุณสามารถทำให้ Google API
การโทรในนามของผู้ใช้ขณะออฟไลน์ เช่น แอปรูปภาพอาจ
ปรับปรุงรูปภาพในอัลบั้ม Google Photos ของผู้ใช้ด้วยการประมวลผลในแบ็กเอนด์
และอัปโหลดผลลัพธ์ไปยังอัลบั้มอื่น ในการดำเนินการดังกล่าว เซิร์ฟเวอร์ของคุณ
ต้องมีโทเค็นเพื่อการเข้าถึงและโทเค็นการรีเฟรช
ในการรับโทเค็นเพื่อการเข้าถึงและรีเฟรชโทเค็นสำหรับเซิร์ฟเวอร์ ให้ทำดังนี้
ขอรหัสการให้สิทธิ์แบบใช้ครั้งเดียวที่เซิร์ฟเวอร์ของคุณแลกเปลี่ยนให้
ทั้ง 2 โทเค็นนี้ หลังจากลงชื่อเข้าใช้สำเร็จ คุณจะเห็นรหัสแบบใช้ครั้งเดียวเป็น
พร็อพเพอร์ตี้ serverAuthCode
ของ GIDSignInResult
ขอรหัสไคลเอ็นต์ของเซิร์ฟเวอร์ หากยังไม่ได้ดำเนินการ
และระบุไว้ในไฟล์ Info.plist
ของแอปใต้รหัสไคลเอ็นต์ OAuth
<key>GIDServerClientID</key>
<string>YOUR_SERVER_CLIENT_ID</string>
ในการเรียกกลับสำหรับการลงชื่อเข้าใช้ ให้เรียกข้อมูลรหัสการให้สิทธิ์แบบครั้งเดียว
Swift
GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in
guard error == nil else { return }
guard let signInResult = signInResult else { return }
let authCode = signInResult.serverAuthCode
}
Objective-C
[GIDSignIn.sharedInstance
signInWithPresentingViewController:self
completion:^(GIDSignInResult * _Nullable signInResult,
NSError * _Nullable error) {
if (error) { return; }
if (signInResult == nil) { return; }
NSString *authCode = signInResult.serverAuthCode;
}];
ส่งสตริง serverAuthCode
ไปยังเซิร์ฟเวอร์ของคุณอย่างปลอดภัยโดยใช้ HTTPS POST
แลกเปลี่ยนรหัสการให้สิทธิ์ในเซิร์ฟเวอร์แบ็กเอนด์ของแอปเพื่อเข้าถึงและรีเฟรช
โทเค็น ใช้โทเค็นเพื่อการเข้าถึงเพื่อเรียกใช้ Google APIs ในนามของผู้ใช้และ
(ไม่บังคับ) จัดเก็บโทเค็นการรีเฟรชเพื่อรับโทเค็นเพื่อการเข้าถึงใหม่เมื่อ
โทเค็นเพื่อการเข้าถึงหมดอายุ
เช่น
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.
String CLIENT_SECRET_FILE = "/path/to/client_secret.json";
// Exchange auth code for access token
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(
JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
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();
String accessToken = tokenResponse.getAccessToken();
// Use access token to call API
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
Drive drive =
new Drive.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential)
.setApplicationName("Auth Code Exchange Demo")
.build();
File file = drive.files().get("appfolder").execute();
// Get profile info from ID token
GoogleIdToken idToken = tokenResponse.parseIdToken();
GoogleIdToken.Payload payload = idToken.getPayload();
String userId = payload.getSubject(); // Use this value as a key to identify a user.
String email = payload.getEmail();
boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
String name = (String) payload.get("name");
String pictureUrl = (String) payload.get("picture");
String locale = (String) payload.get("locale");
String familyName = (String) payload.get("family_name");
String givenName = (String) payload.get("given_name");
Python
from apiclient import discovery
import httplib2
from oauth2client import client
# (Receive auth_code by HTTPS POST)
# If this request does not have `X-Requested-With` header, this could be a CSRF
if not request.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/credentials
CLIENT_SECRET_FILE = '/path/to/client_secret.json'
# Exchange auth code for access token, refresh token, and ID token
credentials = client.credentials_from_clientsecrets_and_code(
CLIENT_SECRET_FILE,
['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
auth_code)
# Call Google API
http_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 token
userid = credentials.id_token['sub']
email = credentials.id_token['email']
เนื้อหาของหน้าเว็บนี้ได้รับอนุญาตภายใต้ใบอนุญาตที่ต้องระบุที่มาของครีเอทีฟคอมมอนส์ 4.0 และตัวอย่างโค้ดได้รับอนุญาตภายใต้ใบอนุญาต Apache 2.0 เว้นแต่จะระบุไว้เป็นอย่างอื่น โปรดดูรายละเอียดที่นโยบายเว็บไซต์ Google Developers Java เป็นเครื่องหมายการค้าจดทะเบียนของ Oracle และ/หรือบริษัทในเครือ
อัปเดตล่าสุด 2025-07-25 UTC
[null,null,["อัปเดตล่าสุด 2025-07-25 UTC"],[[["\u003cp\u003eThis guide enables your servers to make Google API calls on behalf of users, even when they're offline.\u003c/p\u003e\n"],["\u003cp\u003eTo achieve this, your server needs an access token and a refresh token, obtained by exchanging a one-time authorization code.\u003c/p\u003e\n"],["\u003cp\u003eYou need to integrate basic Google Sign-In and configure a server client ID in your app's \u003ccode\u003eInfo.plist\u003c/code\u003e file.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves retrieving the authorization code on the client-side, sending it to your server, and exchanging it for tokens on the server.\u003c/p\u003e\n"],["\u003cp\u003eYour server can then use the access token to make API calls and optionally store the refresh token for future use.\u003c/p\u003e\n"]]],[],null,["Follow this procedure if you want your servers to be able to make\nGoogle API calls on behalf of users or while they are offline.\n\nBefore you begin\n\nYou must complete the [basic Google Sign-In integration](/identity/sign-in/ios/sign-in).\n\nEnable server-side API access for your app\n\nOn the [Access Google APIs in an iOS app](/identity/sign-in/ios/api-access)\npage, your app authenticates the user on the client side only; in that case,\nyour app is able to access Google APIs only while the user is actively using\nyour app.\n\nWith the procedure described on this page, your servers can make Google API\ncalls on behalf of users while they are offline. For example, a photo app could\nenhance a photo in a user's Google Photos album by processing it on a backend\nserver and uploading the result to another album. To do this, your server\nrequires an access token and a refresh token.\n\nTo obtain an access token and refresh token for your server, you can\nrequest a one-time authorization code that your server exchanges for\nthese two tokens. After a successful sign-in, you will find the one-time code as\nthe `serverAuthCode` property of `GIDSignInResult`.\n\n1. If you haven't already, [get a server client ID](/identity/sign-in/ios/start-integrating#server_client_id)\n and specify it in your app's `Info.plist` file, [below your OAuth client ID](/identity/sign-in/ios/start-integrating#add_client_id).\n\n \u003cbr /\u003e\n\n ```scdoc\n \u003ckey\u003eGIDServerClientID\u003c/key\u003e\n \u003cstring\u003eYOUR_SERVER_CLIENT_ID\u003c/string\u003e\n ```\n\n \u003cbr /\u003e\n\n2. In your sign-in callback, retrieve the one-time authorization code:\n\n Swift \n\n GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in\n guard error == nil else { return }\n guard let signInResult = signInResult else { return }\n\n let authCode = signInResult.serverAuthCode\n }\n\n Objective-C \n\n [GIDSignIn.sharedInstance\n signInWithPresentingViewController:self\n completion:^(GIDSignInResult * _Nullable signInResult,\n NSError * _Nullable error) {\n if (error) { return; }\n if (signInResult == nil) { return; }\n\n NSString *authCode = signInResult.serverAuthCode;\n }];\n\n3. Securely pass the `serverAuthCode` string to your server using HTTPS POST.\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 For example: \n\n Java \n\n ```java\n // (Receive authCode via HTTPS POST)\n\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\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 \u003cbr /\u003e"]]