ด้วยขั้นตอนเพิ่มการลงชื่อเข้าใช้ ก่อนหน้านี้ แอปของคุณจะตรวจสอบสิทธิ์ผู้ใช้ในฝั่งไคลเอ็นต์เท่านั้น ในกรณีดังกล่าว คุณจะเข้าถึง Google API ได้ในขณะที่ผู้ใช้กำลังใช้แอปของคุณอยู่เท่านั้น หากต้องการให้เซิร์ฟเวอร์ของคุณสามารถเรียกใช้ Google API ในนามของ ผู้ใช้ได้ (อาจเป็นขณะที่ผู้ใช้ออฟไลน์อยู่) เซิร์ฟเวอร์ของคุณจะต้องมีโทเค็น การเข้าถึง
ก่อนเริ่มต้น
- กำหนดค่าโปรเจ็กต์ใน Android Studio
- เพิ่มปุ่มลงชื่อเข้าใช้ด้วย Google ลงในแอป
- สร้างรหัสไคลเอ็นต์เว็บแอปพลิเคชัน OAuth 2.0 สำหรับเซิร์ฟเวอร์แบ็กเอนด์ รหัสไคลเอ็นต์นี้ แตกต่างจากรหัสไคลเอ็นต์ของแอป คุณค้นหาหรือสร้างรหัสไคลเอ็นต์สำหรับเซิร์ฟเวอร์ได้ในคอนโซล Google API
เปิดใช้การเข้าถึง API ฝั่งเซิร์ฟเวอร์สำหรับแอป
- เมื่อกําหนดค่าการลงชื่อเข้าใช้ด้วย Google ให้สร้างออบเจ็กต์ - GoogleSignInOptionsด้วยเมธอด- requestServerAuthCodeและระบุขอบเขตที่แบ็กเอนด์ของแอปต้องเข้าถึงด้วยเมธอด [- requestScopes][55]- ส่งรหัสไคลเอ็นต์ของเซิร์ฟเวอร์ไปยังเมธอด - 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. String serverClientId = getString(R.string.server_client_id); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER)) .requestServerAuthCode(serverClientId) .requestEmail() .build(); 
- หลังจากผู้ใช้ลงชื่อเข้าใช้สำเร็จแล้ว ให้รับรหัสการให้สิทธิ์สำหรับผู้ใช้ด้วย - getServerAuthCode- Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { GoogleSignInAccount account = task.getResult(ApiException.class); String authCode = account.getServerAuthCode(); // Show signed-un UI updateUI(account); // TODO(developer): send code to server and exchange for access/refresh/ID tokens } catch (ApiException e) { Log.w(TAG, "Sign-in failed", e); updateUI(null); }
- ส่งรหัสการให้สิทธิ์ไปยังแบ็กเอนด์ของแอปโดยใช้ HTTPS POST ดังนี้ - HttpPost httpPost = new HttpPost("https://yourbackend.example.com/authcode"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("authCode", authCode)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); final String responseBody = EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { Log.e(TAG, "Error sending auth code to backend.", e); } catch (IOException e) { Log.e(TAG, "Error sending auth code to backend.", e); }
- ในเซิร์ฟเวอร์แบ็กเอนด์ของแอป ให้แลกรหัสการให้สิทธิ์เป็นโทเค็นเพื่อการเข้าถึงและโทเค็นการรีเฟรช ใช้โทเค็นเพื่อการเข้าถึงเพื่อเรียกใช้ Google API ในนามของผู้ใช้ และจัดเก็บโทเค็นการรีเฟรช (ไม่บังคับ) เพื่อรับโทเค็นเพื่อการเข้าถึงใหม่เมื่อโทเค็นเพื่อการเข้าถึงหมดอายุ - หากขอสิทธิ์เข้าถึงโปรไฟล์ คุณจะได้รับโทเค็นรหัสที่มี ข้อมูลโปรไฟล์พื้นฐานของผู้ใช้ด้วย - เช่น - 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'] 
[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...)
