總覽
目的:本文件說明適用於 Java 的 Google OAuth 用戶端程式庫提供的一般 OAuth 2.0 功能。您可以使用這些函式對任何網際網路服務進行驗證和授權。
如需使用 GoogleCredential
對 Google 服務執行 OAuth 2.0 授權的操作說明,請參閱搭配使用 OAuth 2.0 與 Java 適用的 Google API 用戶端程式庫。
摘要: OAuth 2.0 是標準規格,可讓使用者安全地授權用戶端應用程式存取受保護的伺服器端資源。此外,OAuth 2.0 不記名權杖規格也將說明如何使用在使用者授權過程中授予的存取權杖來存取這些受保護的資源。
如需詳細資訊,請參閱下列套件的 Javadoc 說明文件:
- com.google.api.client.auth.oauth2 (來自 google-oauth-client)
- com.google.api.client.extensions.servlet.auth.oauth2 (from google-oauth-client-servlet)
- com.google.api.client.extensions.appengine.auth.oauth2 (from google-oauth-client-appengine)
客戶註冊
使用 Java 適用的 Google OAuth 用戶端程式庫之前,您可能需要向授權伺服器註冊應用程式,才能接收用戶端 ID 和用戶端密鑰。(如需這項程序的一般資訊,請參閱「用戶端註冊規格」)。
憑證和憑證存放區
憑證是執行緒安全的 OAuth 2.0 輔助類別,可用來透過存取權杖存取受保護的資源。使用更新權杖時,Credential
在使用更新權杖過期時,也會重新整理存取權杖。舉例來說,如果您已經有存取權杖,可以透過下列方式提出要求:
public static HttpResponse executeGet( HttpTransport transport, JsonFactory jsonFactory, String accessToken, GenericUrl url) throws IOException { Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); return requestFactory.buildGetRequest(url).execute(); }
大多數應用程式都需要保留憑證的存取權杖並更新權杖,避免日後再重新導向至瀏覽器中的授權頁面。這個程式庫中的 CredentialStore 實作已淘汰,將於日後的版本中移除。另一個方法是將 DataStoreFactory 和 DataStore 介面與 StoredCredential 搭配使用,後者由 Java 適用的 Google HTTP 用戶端程式庫提供。
您可以使用程式庫提供的下列其中一個實作方式:
- JdoDataStoreFactory 會使用 JDO 保留憑證。
- AppEngineDataStoreFactory 會使用 Google App Engine Data Store API 保留憑證。
- MemoryDataStoreFactory 會將憑證「保留」在記憶體中,該憑證僅可做為程序生命週期的短期儲存空間。
- FileDataStoreFactory 會保留檔案中的憑證。
Google App Engine 使用者:
AppEngineCredentialStore 已淘汰,並即將移除。
建議您搭配使用 AppEngineDataStoreFactory 與 StoredCredential。如果您已以舊有方式儲存憑證,可以使用新增的輔助方法 migrationTo(AppEngineDataStoreFactory) 或 migrationTo(DataStore) 進行遷移。
使用 DataStoreCredentialRefreshListener,並透過 GoogleCredential.Builder.addRefreshListener(CredentialRefreshListener) 設為憑證。
授權碼流程
使用授權碼流程,讓使用者可授予應用程式存取其受保護資料的權限。如需這個流程的通訊協定,請參閱授權碼授權規格。
此流程是使用 AuthorizationCodeFlow 進行實作。步驟如下:
- 使用者登入您的應用程式。您需要將該使用者與應用程式專屬的使用者 ID 建立關聯。
- 根據使用者 ID 呼叫 AuthorizationCodeFlow.loadCredential(String),檢查使用者的憑證是否已知。如果是,這樣就大功告成了。
- 如果沒有,請呼叫 AuthorizationCodeFlow.newAuthorizationUrl(),並將使用者的瀏覽器導向至授權頁面,透過該頁面即可授予應用程式存取受保護資料的權限。
- 接著,網路瀏覽器會透過「程式碼」查詢參數重新導向至重新導向網址,然後接著就能使用 AuthorizationCodeFlow.newTokenRequest(String) 要求存取權杖。
- 使用 AuthorizationCodeFlow.createAndStoreCredential(TokenResponse, String) 來儲存並取得存取受保護資源的憑證。
如果您並未使用 AuthorizationCodeFlow,則可使用較低層級的類別:
- 根據使用者 ID,使用 DataStore.get(String) 從商店載入憑證。
- 使用 AuthorizationCodeRequestUrl 將瀏覽器導向授權頁面。
- 請使用 AuthorizationCodeResponseUrl 來處理授權回應並剖析授權碼。
- 請使用 AuthorizationCodeTokenRequest 要求存取權杖,並可能產生更新權杖。
- 建立新的憑證,並使用 DataStore.set(String, V) 儲存憑證。
- 使用憑證存取受保護的資源。過期的存取權杖會自動使用更新權杖 (在適用情況下) 重新整理。請務必使用 DataStoreCredentialRefreshListener,並使用 Credential.Builder.addRefreshListener(CredentialRefreshListener) 設為憑證。
LL 授權碼流程
這個程式庫提供 JAR 輔助類別,可大幅簡化基本用途的授權碼流程。您只需提供 AbstractAuthorizationCodeServlet 和 AbstractAuthorizationCodeCallbackServlet (來自 google-oauth-client-servlet) 的具體子類別,並將其新增至 web.xml 檔案即可。請注意,您仍需處理網頁應用程式的使用者登入及擷取使用者 ID,
程式碼範例:
public class ServletSample extends AbstractAuthorizationCodeServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // do stuff } @Override protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException { GenericUrl url = new GenericUrl(req.getRequestURL().toString()); url.setRawPath("/oauth2callback"); return url.build(); } @Override protected AuthorizationCodeFlow initializeFlow() throws IOException { return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), new NetHttpTransport(), new JacksonFactory(), new GenericUrl("https://server.example.com/token"), new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw"), "s6BhdRkqt3", "https://server.example.com/authorize").setCredentialDataStore( StoredCredential.getDefaultDataStore( new FileDataStoreFactory(new File("datastoredir")))) .build(); } @Override protected String getUserId(HttpServletRequest req) throws ServletException, IOException { // return user ID } } public class ServletCallbackSample extends AbstractAuthorizationCodeCallbackServlet { @Override protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential) throws ServletException, IOException { resp.sendRedirect("/"); } @Override protected void onError( HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse) throws ServletException, IOException { // handle error } @Override protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException { GenericUrl url = new GenericUrl(req.getRequestURL().toString()); url.setRawPath("/oauth2callback"); return url.build(); } @Override protected AuthorizationCodeFlow initializeFlow() throws IOException { return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), new NetHttpTransport(), new JacksonFactory(), new GenericUrl("https://server.example.com/token"), new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw"), "s6BhdRkqt3", "https://server.example.com/authorize").setCredentialDataStore( StoredCredential.getDefaultDataStore( new FileDataStoreFactory(new File("datastoredir")))) .build(); } @Override protected String getUserId(HttpServletRequest req) throws ServletException, IOException { // return user ID } }
Google App Engine 授權碼流程
App Engine 上的授權碼流程與 sys 授權碼流程幾乎相同,不過我們可以使用 Google App Engine 的 Users Java API。使用者必須先登入,才能啟用 Users Java API。如需將使用者重新導向登入頁面的相關資訊,請參閱 web.xml 中的安全性與驗證。
與 JAR 案例的主要差異在於,您須提供 AbstractAppEngineAuthorizationCodeServlet 和 AbstractAppEngineAuthorizationCodeCallbackServlet (來自 google-oauth-client-appengine) 的具體子類別。這些類別會擴充抽象 AVD 類別,並使用 Users Java API 為您實作 getUserId
方法。AppEngineDataStoreFactory (來自 Java 的 Google HTTP 用戶端程式庫) 是使用 Google App Engine Data Store API 保留憑證的好方法。
程式碼範例:
public class AppEngineSample extends AbstractAppEngineAuthorizationCodeServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // do stuff } @Override protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException { GenericUrl url = new GenericUrl(req.getRequestURL().toString()); url.setRawPath("/oauth2callback"); return url.build(); } @Override protected AuthorizationCodeFlow initializeFlow() throws IOException { return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), new UrlFetchTransport(), new JacksonFactory(), new GenericUrl("https://server.example.com/token"), new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw"), "s6BhdRkqt3", "https://server.example.com/authorize").setCredentialStore( StoredCredential.getDefaultDataStore(AppEngineDataStoreFactory.getDefaultInstance())) .build(); } } public class AppEngineCallbackSample extends AbstractAppEngineAuthorizationCodeCallbackServlet { @Override protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential) throws ServletException, IOException { resp.sendRedirect("/"); } @Override protected void onError( HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse) throws ServletException, IOException { // handle error } @Override protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException { GenericUrl url = new GenericUrl(req.getRequestURL().toString()); url.setRawPath("/oauth2callback"); return url.build(); } @Override protected AuthorizationCodeFlow initializeFlow() throws IOException { return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), new UrlFetchTransport(), new JacksonFactory(), new GenericUrl("https://server.example.com/token"), new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw"), "s6BhdRkqt3", "https://server.example.com/authorize").setCredentialStore( StoredCredential.getDefaultDataStore(AppEngineDataStoreFactory.getDefaultInstance())) .build(); } }
指令列授權碼流程
從 dailymotion-cmdline-sample 取得的簡化程式碼範例:
/** Authorizes the installed application to access user's protected data. */ private static Credential authorize() throws Exception { OAuth2ClientCredentials.errorIfNotSpecified(); // set up authorization code flow AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken .authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(TOKEN_SERVER_URL), new ClientParametersAuthentication( OAuth2ClientCredentials.API_KEY, OAuth2ClientCredentials.API_SECRET), OAuth2ClientCredentials.API_KEY, AUTHORIZATION_SERVER_URL).setScopes(Arrays.asList(SCOPE)) .setDataStoreFactory(DATA_STORE_FACTORY).build(); // authorize LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost( OAuth2ClientCredentials.DOMAIN).setPort(OAuth2ClientCredentials.PORT).build(); return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); } private static void run(HttpRequestFactory requestFactory) throws IOException { DailyMotionUrl url = new DailyMotionUrl("https://api.dailymotion.com/videos/favorites"); url.setFields("id,tags,title,url"); HttpRequest request = requestFactory.buildGetRequest(url); VideoFeed videoFeed = request.execute().parseAs(VideoFeed.class); ... } public static void main(String[] args) { ... DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); final Credential credential = authorize(); HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) throws IOException { credential.initialize(request); request.setParser(new JsonObjectParser(JSON_FACTORY)); } }); run(requestFactory); ... }
瀏覽器用戶端流程
以下是隱式授權規格中所述,以瀏覽器為基礎的用戶端流程常見步驟:
- 使用 BrowserClientRequestUrl 將使用者的瀏覽器重新導向至授權頁面,使用者可在該頁面授予應用程式存取受保護資料的存取權。
- 使用 JavaScript 應用程式,處理向授權伺服器註冊的重新導向 URI 網址片段中找到的存取權杖。
網頁應用程式的使用範例:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = new BrowserClientRequestUrl( "https://server.example.com/authorize", "s6BhdRkqt3").setState("xyz") .setRedirectUri("https://client.example.com/cb").build(); response.sendRedirect(url); }
偵測過期的存取權杖
根據 OAuth 2.0 熊規格,呼叫伺服器以存取過期存取權杖的受保護資源時,伺服器通常會傳回 HTTP 401 Unauthorized
狀態碼,例如:
HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer realm="example", error="invalid_token", error_description="The access token expired"
不過,這個規格似乎有許多彈性調整。詳情請參閱 OAuth 2.0 提供者的說明文件。
另一種方法是檢查存取權杖回應中的 expires_in
參數。這會指定已授予存取權杖的生命週期 (以秒為單位),通常為一個小時。不過,存取權杖實際上可能不會在這個期間結束時過期,而伺服器可能會繼續允許存取。因此,我們通常建議等待 401 Unauthorized
狀態碼,而不要假設權杖過期以經過時間為準。或者,您可以嘗試在存取權杖過期前不久重新整理;如果權杖伺服器無法使用,請繼續使用存取權杖,直到收到 401
。這是憑證中預設使用的策略。
另一個選擇是在每次要求前擷取新的存取權杖,但每次要求時都需要對權杖伺服器傳送額外的 HTTP 要求,因此速度和網路用量可能有負面選擇。在理想情況下,請將存取權杖儲存在安全的永久儲存空間中,盡可能減少應用程式對新存取權杖的要求。(但對於已安裝的應用程式,安全儲存空間會是個難題)。
請注意,存取權杖會因為到期時間以外的原因而失效,例如使用者已明確撤銷權杖,因此請確保錯誤處理程式碼保持完善可靠。偵測到權杖失效後 (例如權杖已失效或遭撤銷) 後,您必須從儲存空間中移除存取權杖。舉例來說,在 Android 上,您必須呼叫 AccountManager.invalidateAuthToken。