将 OAuth 2.0 与适用于 Java 的 Google API 客户端库搭配使用

概览

用途:本文档介绍了如何使用 GoogleCredential 实用程序类通过 Google 服务进行 OAuth 2.0 授权。如需了解我们提供的通用 OAuth 2.0 函数,请参阅 OAuth 2.0 和适用于 Java 的 Google OAuth 客户端库

总结:如需访问存储在 Google 服务中的受保护数据,请使用 OAuth 2.0 进行授权。Google API 支持适用于不同类型客户端应用的 OAuth 2.0 流程。在所有这些流程中,客户端应用都会请求一个仅与您的客户端应用和所访问受保护数据的所有者相关联的访问令牌。访问令牌还与一个有限的范围相关联,该范围定义了客户端应用可以访问的数据类型(例如“管理您的任务”)。OAuth 2.0 的一个重要目标是提供对受保护数据的安全便捷访问,同时最大限度地减少访问令牌被盗时可能造成的影响。

Java 版 Google API 客户端库中的 OAuth 2.0 软件包基于通用的 Java 版 Google OAuth 2.0 客户端库构建。

如需了解详情,请参阅以下软件包的 Javadoc 文档:

Google API 控制台

在访问 Google API 之前,您需要在 Google API 控制台中设置一个项目,以用于身份验证和结算,无论您的客户端是已安装的应用、移动应用、Web 服务器还是在浏览器中运行的客户端。

如需了解如何正确设置凭据,请参阅 API 控制台帮助

凭据

GoogleCredential

GoogleCredential 是一个线程安全的 OAuth 2.0 辅助类,用于使用访问令牌访问受保护的资源。例如,如果您已有访问令牌,则可以按以下方式发出请求:

GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
Plus plus = new Plus.builder(new NetHttpTransport(),
                             GsonFactory.getDefaultInstance(),
                             credential)
    .setApplicationName("Google-PlusSample/1.0")
    .build();

Google App Engine 身份

此替代凭据基于 Google App Engine App Identity Java API。与客户端应用请求访问最终用户数据的凭据不同,App Identity API 提供对客户端应用自身数据的访问权限。

使用 AppIdentityCredential(来自 google-api-client-appengine)。这种凭据要简单得多,因为 Google App Engine 会处理所有细节。您只需指定所需的 OAuth 2.0 范围。

以下示例代码取自 urlshortener-robots-appengine-sample

static Urlshortener newUrlshortener() {
  AppIdentityCredential credential =
      new AppIdentityCredential(
          Collections.singletonList(UrlshortenerScopes.URLSHORTENER));
  return new Urlshortener.Builder(new UrlFetchTransport(),
                                  GsonFactory.getDefaultInstance(),
                                  credential)
      .build();
}

数据存储区

访问令牌的有效期通常为 1 小时;如果您在超出该时间后尝试使用它,系统会报错。 GoogleCredential 负责自动“刷新”令牌,即获得新的访问令牌。这是通过长期刷新令牌完成的,如果您在授权代码流程中使用 access_type=offline 参数,则通常会随访问令牌一起收到该令牌(请参阅 GoogleAuthorizationCodeFlow.Builder.setAccessType(String))。

大多数应用都需要持久保留凭据的访问令牌和/或刷新令牌。如需持久保留凭据的访问令牌和/或刷新令牌,您可以提供自己的 DataStoreFactory 实现(使用 StoredCredential);也可以使用库提供的以下实现之一:

AppEngine 用户AppEngineCredentialStore 已弃用,很快就会被移除。我们建议您将 AppEngineDataStoreFactoryStoredCredential 搭配使用。 如果您以旧方式存储了凭据,可以使用新增的辅助方法 migrateTo(AppEngineDataStoreFactory)migrateTo(DataStore) 来执行迁移。

您可以使用 DataStoreCredentialRefreshListener,并使用 GoogleCredential.Builder.addRefreshListener(CredentialRefreshListener) 为凭据设置该监听器。

授权代码流程

使用授权码流程,让最终用户向您的应用授予访问其在 Google API 上受保护的数据的权限。此流程的协议在授权代码授权中指定。

此流程是使用 GoogleAuthorizationCodeFlow 实现的。具体步骤包括:

或者,如果您不使用 GoogleAuthorizationCodeFlow,则可以使用较低级别的类:

Google API 控制台中设置项目时,您需要根据所用的流程选择不同的凭据。如需了解详情,请参阅设置 OAuth 2.0OAuth 2.0 场景。 以下是每种流程的代码段。

Web 服务器应用

如需了解此流程的协议,请参阅针对网络服务器应用使用 OAuth 2.0

此库提供 servlet 辅助类,可显著简化基本用例的授权代码流程。您只需提供 AbstractAuthorizationCodeServletAbstractAuthorizationCodeCallbackServlet(来自 google-oauth-client-servlet)的具体子类,并将它们添加到您的 web.xml 文件中。请注意,您仍然需要负责处理 Web 应用的用户登录事宜并提取用户 ID。

public class CalendarServletSample 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 GoogleAuthorizationCodeFlow.Builder(
        new NetHttpTransport(), GsonFactory.getDefaultInstance(),
        "[[ENTER YOUR CLIENT ID]]", "[[ENTER YOUR CLIENT SECRET]]",
        Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
        DATA_STORE_FACTORY).setAccessType("offline").build();
  }

  @Override
  protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
    // return user ID
  }
}

public class CalendarServletCallbackSample 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 GoogleAuthorizationCodeFlow.Builder(
        new NetHttpTransport(), GsonFactory.getDefaultInstance()
        "[[ENTER YOUR CLIENT ID]]", "[[ENTER YOUR CLIENT SECRET]]",
        Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
        DATA_STORE_FACTORY).setAccessType("offline").build();
  }

  @Override
  protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
    // return user ID
  }
}

Google App Engine 应用

App Engine 上的授权代码流程与 servlet 授权代码流程几乎完全相同,只不过我们可以利用 Google App Engine 的 Users Java API。用户需要登录才能启用 Users Java API;如需了解在用户尚未登录时将其重定向到登录页面的相关信息,请参阅 Security and Authentication (in web.xml)。

与 servlet 的主要区别在于,您需要提供 AbstractAppEngineAuthorizationCodeServletAbstractAppEngineAuthorizationCodeCallbackServlet(来自 google-oauth-client-appengine)的具体子类。它们扩展了抽象 servlet 类,并使用 Users Java API 为您实现了 getUserId 方法。AppEngineDataStoreFactory(来自 google-http-client-appengine)是使用 Google App Engine DataStore API 持久保存凭据的理想选择。

以下示例(略有修改)取自 calendar-appengine-sample

public class CalendarAppEngineSample extends AbstractAppEngineAuthorizationCodeServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    // do stuff
  }

  @Override
  protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
    return Utils.getRedirectUri(req);
  }

  @Override
  protected AuthorizationCodeFlow initializeFlow() throws IOException {
    return Utils.newFlow();
  }
}

class Utils {
  static String getRedirectUri(HttpServletRequest req) {
    GenericUrl url = new GenericUrl(req.getRequestURL().toString());
    url.setRawPath("/oauth2callback");
    return url.build();
  }

  static GoogleAuthorizationCodeFlow newFlow() throws IOException {
    return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
        getClientCredential(), Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
        DATA_STORE_FACTORY).setAccessType("offline").build();
  }
}

public class OAuth2Callback extends AbstractAppEngineAuthorizationCodeCallbackServlet {

  private static final long serialVersionUID = 1L;

  @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 {
    String nickname = UserServiceFactory.getUserService().getCurrentUser().getNickname();
    resp.getWriter().print("<h3>" + nickname + ", why don't you want to play with me?</h1>");
    resp.setStatus(200);
    resp.addHeader("Content-Type", "text/html");
  }

  @Override
  protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
    return Utils.getRedirectUri(req);
  }

  @Override
  protected AuthorizationCodeFlow initializeFlow() throws IOException {
    return Utils.newFlow();
  }
}

如需查看其他示例,请参阅 storage-serviceaccount-appengine-sample

服务账号

GoogleCredential 还支持服务账号。与客户端应用请求访问最终用户数据的凭据不同,服务账号可让客户端应用访问其自身的数据。您的客户端应用使用从 Google API 控制台下载的私钥对访问令牌请求进行签名。

用法示例:

HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
...
// Build service account credential.

GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("MyProject-1234.json"))
    .createScoped(Collections.singleton(PlusScopes.PLUS_ME));
// Set up global Plus instance.
plus = new Plus.Builder(httpTransport, jsonFactory, credential)
    .setApplicationName(APPLICATION_NAME).build();
...

如需查看其他示例,请参阅 storage-serviceaccount-cmdline-sample

冒充别人

您还可以使用服务账号流程来模拟您拥有的网域中的用户。这与上面的服务账号流程非常相似,但您还需要调用 GoogleCredential.Builder.setServiceAccountUser(String)

已安装的应用

这是为已安装的应用使用 OAuth 2.0 中所述的命令行授权代码流程。

用法示例:

public static void main(String[] args) {
  try {
    httpTransport = new NetHttpTransport();
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
    // authorization
    Credential credential = authorize();
    // set up global Plus instance
    plus = new Plus.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(
        APPLICATION_NAME).build();
   // ...
}

private static Credential authorize() throws Exception {
  // load client secrets
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
      new InputStreamReader(PlusSample.class.getResourceAsStream("/client_secrets.json")));
  // set up authorization code flow
  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport, JSON_FACTORY, clientSecrets,
      Collections.singleton(PlusScopes.PLUS_ME)).setDataStoreFactory(
      dataStoreFactory).build();
  // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

客户端应用

如需使用针对客户端应用使用 OAuth 2.0 中所述的基于浏览器的客户端流程,您通常需要执行以下步骤:

  1. 使用 GoogleBrowserClientRequestUrl 将浏览器中的最终用户重定向到授权页面,以向浏览器应用授予对最终用户受保护数据的访问权限。
  2. 使用 JavaScript 版 Google API 客户端库处理在 Google API 控制台中注册的重定向 URI 的网址 fragment 中找到的访问令牌。

Web 应用的用法示例:

public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException {
  String url = new GoogleBrowserClientRequestUrl("812741506391.apps.googleusercontent.com",
      "https://oauth2.example.com/oauthcallback", Arrays.asList(
          "https://www.googleapis.com/auth/userinfo.email",
          "https://www.googleapis.com/auth/userinfo.profile")).setState("/profile").build();
  response.sendRedirect(url);
}

Android

@Beta

应将哪个库与 Android 搭配使用

如果您正在为 Android 开发应用,并且想要使用的 Google API 包含在 Google Play 服务库中,请使用该库以获得最佳性能和体验。如果您想在 Android 中使用的 Google API 不属于 Google Play 服务库,则可以使用 Google API 客户端库(适用于 Java),该库支持 Android 4.0(Ice Cream Sandwich)或更高版本,并且在此处进行了说明。Java 版 Google API 客户端库对 Android 的支持为 @Beta

背景信息

从 Eclair (SDK 2.1) 开始,用户账号在 Android 设备上使用账号管理器进行管理。所有 Android 应用授权均由 SDK 使用 AccountManager 集中管理。您指定应用所需的 OAuth 2.0 范围,然后它会返回一个可供使用的访问令牌。

OAuth 2.0 范围通过 authTokenType 参数指定为 oauth2: 加范围。例如:

oauth2:https://www.googleapis.com/auth/tasks

此权限指定对 Google Tasks API 的读写权限。如果您需要多个 OAuth 2.0 范围,请使用以空格分隔的列表。

某些 API 也有特殊的 authTokenType 参数。例如,“管理您的任务”是上述 authtokenType 示例的别名。

您还必须指定 Google API 控制台中的 API 密钥。 否则,AccountManager 提供给您的令牌只会为您提供匿名配额,而匿名配额通常非常低。相比之下,如果您指定 API 密钥,则可获得更高的免费配额,并且可以选择为超出该配额的用量设置结算。

以下示例代码段取自 tasks-android-sample

com.google.api.services.tasks.Tasks service;

@Override
public void onCreate(Bundle savedInstanceState) {
  credential =
      GoogleAccountCredential.usingOAuth2(this, Collections.singleton(TasksScopes.TASKS));
  SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
  credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
  service =
      new com.google.api.services.tasks.Tasks.Builder(httpTransport, jsonFactory, credential)
          .setApplicationName("Google-TasksAndroidSample/1.0").build();
}

private void chooseAccount() {
  startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  switch (requestCode) {
    case REQUEST_GOOGLE_PLAY_SERVICES:
      if (resultCode == Activity.RESULT_OK) {
        haveGooglePlayServices();
      } else {
        checkGooglePlayServicesAvailable();
      }
      break;
    case REQUEST_AUTHORIZATION:
      if (resultCode == Activity.RESULT_OK) {
        AsyncLoadTasks.run(this);
      } else {
        chooseAccount();
      }
      break;
    case REQUEST_ACCOUNT_PICKER:
      if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
        String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
        if (accountName != null) {
          credential.setSelectedAccountName(accountName);
          SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
          SharedPreferences.Editor editor = settings.edit();
          editor.putString(PREF_ACCOUNT_NAME, accountName);
          editor.commit();
          AsyncLoadTasks.run(this);
        }
      }
      break;
  }
}