如要在使用者離線時代表使用者使用 Google 服務,您必須採用混合型伺服器端流程,讓使用者透過 JavaScript API 用戶端在用戶端授權您的應用程式,並將特殊的一次性授權碼傳送至伺服器。您的伺服器會交換這個一次性代碼,向 Google 取得自己的存取和更新權杖,讓伺服器能夠自行發出 API 呼叫,且可在使用者離線時執行。相較於單純的伺服器端流程,以及將存取權杖傳送至伺服器,這種一次性程式碼流程都具備安全性優勢。
為取得伺服器端應用程式存取權杖的登入流程如下圖所示。
一次性驗證碼具備幾項安全優勢。透過程式碼,Google 會直接將權杖提供給伺服器,不需要任何中繼憑證。雖然我們不建議洩漏程式碼,但少了用戶端密鑰卻非常難以使用。妥善保管用戶端密鑰!
實作一次性代碼流程
Google 登入按鈕會提供存取權杖和授權碼。這組代碼是一次性代碼,可供伺服器與 Google 伺服器交換,以取得存取權杖。
以下程式碼範例示範如何執行一次性代碼流程。
透過一次性代碼流程驗證 Google 登入時,您必須完成以下事項:
步驟 1:建立用戶端 ID 和用戶端密鑰
如要建立用戶端 ID 和用戶端密鑰,請建立 Google API 控制台專案,設定 OAuth 用戶端 ID,並註冊 JavaScript 來源:
前往 Google API 控制台。
從專案下拉式選單中選取現有專案,或選取 [Create a new project] (建立新專案) 來建立新專案。
在「API 和服務」下方的側欄中,選取「憑證」,然後按一下「設定同意畫面」。
選擇電子郵件地址並指定產品名稱,然後按下「儲存」。
在「Credentials」分頁中,選取「Create credentials」下拉式清單,然後選擇「OAuth client ID」。
在「Application type」(應用程式類型) 下方,選取 [Web application] (網頁應用程式)。
按照下列方式註冊應用程式可存取 Google API 的來源。來源是通訊協定、主機名稱和通訊埠的不重複組合。
在「Authorized JavaScript origins」(已授權的 JavaScript 來源) 欄位輸入應用程式來源。您可以輸入多個來源,讓應用程式在不同通訊協定、網域或子網域上執行。您無法使用萬用字元。在以下範例中,第二個網址可能是實際執行網址。
http://localhost:8080 https://myproductionurl.example.com
「授權的重新導向 URI」欄位不需要輸入值。重新導向 URI 不會與 JavaScript API 搭配使用。
按下「建立」按鈕。
畫面中會顯示「OAuth 用戶端」對話方塊,然後複製「用戶端 ID」。用戶端 ID 可讓應用程式存取已啟用的 Google API。
步驟 2:在您的頁面中加入 Google 平台程式庫
請加入下列指令碼來示範匿名函式,這個函式會將指令碼插入這個 index.html
網頁的 DOM。
<!-- The top of file index.html -->
<html itemscope itemtype="http://schema.org/Article">
<head>
<!-- BEGIN Pre-requisites -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer>
</script>
<!-- END Pre-requisites -->
步驟 3:初始化 GoogleAuth 物件
載入 auth2 程式庫並呼叫 gapi.auth2.init()
,藉此初始化 GoogleAuth
物件。在呼叫 init()
時,指定用戶端 ID 和要要求的範圍。
<!-- Continuing the <head> section -->
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
// Scopes to request in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
});
}
</script>
</head>
<body>
<!-- ... -->
</body>
</html>
步驟 4:在網頁中新增登入按鈕
在網頁中加入登入按鈕,並附加點擊處理常式呼叫 grantOfflineAccess()
以啟動一次性程式碼流程。
<!-- Add where you want your sign-in button to render -->
<!-- Use an image that follows the branding guidelines in a real app -->
<button id="signinButton">Sign in with Google</button>
<script>
$('#signinButton').click(function() {
// signInCallback defined in step 6.
auth2.grantOfflineAccess().then(signInCallback);
});
</script>
步驟 5:登入使用者
使用者按一下登入按鈕,即可授權應用程式存取您要求的權限。接著,您在 grantOfflineAccess().then()
方法中指定的回呼函式會傳遞包含授權碼的 JSON 物件。例如:
{"code":"4/yU4cQZTMnnMtetyFcIWNItG32eKxxxgXXX-Z4yyJJJo.4qHskT-UtugceFc0ZRONyF4z7U4UmAI"}
步驟 6:將授權碼傳送至伺服器
code
是一次性代碼,可供伺服器交換自己的存取權杖和更新權杖。系統向使用者顯示要求離線存取權的授權對話方塊後,您才能取得更新權杖。如果您已在步驟 4 的 OfflineAccessOptions
中指定 select-account
prompt
,就必須儲存擷取的更新權杖以供日後使用,因為後續的廣告交易平台會針對更新權杖傳回 null
。這個流程可進一步提高標準 OAuth 2.0 流程的安全性。
系統傳回的存取權杖一律會與有效的授權碼交換。
下列指令碼定義了登入按鈕的回呼函式。登入成功後,函式會儲存存取權杖以供用戶端使用,並將一次性代碼傳送至相同網域上的伺服器。
<!-- Last part of BODY element in file index.html -->
<script>
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'POST',
url: 'http://example.com/storeauthcode',
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
} else {
// There was an error.
}
}
</script>
步驟 7:透過授權碼交換存取權杖
在伺服器上交換驗證碼,以取得存取和更新權杖。請使用存取權杖代表使用者呼叫 Google API,並視需要儲存更新權杖,方便在存取權杖過期時取得新的存取權杖。
如果您要求存取設定檔,也會取得包含使用者基本個人資訊的 ID 權杖。
範例如下:
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']