使用OAuth检索访问令牌而不重定向到网页

时间:2014-07-01 17:02:04

标签: api google-app-engine oauth google-oauth

我编写了一个java程序,它使用客户端ID和客户端密钥进行身份验证。当我运行我的程序时,它会提供一个URL,当我转到该URL时,它会给我访问令牌。如何在不使用浏览器的情况下以编程方式获取访问令牌?

我的代码:

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.DirectoryScopes;
import com.google.api.services.admin.directory.model.User;
import com.google.api.services.admin.directory.model.Users;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;


public class DirectoryCommandLine {

  private static String CLIENT_ID = "YOUR_CLIENT_ID";
  private static String CLIENT_SECRET = "YOUR_CLIENT_SECRET";

  private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

  public static void main(String[] args) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER))
        .setAccessType("online")
        .setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
    System.out.println("Please open the following URL in your browser then type the authorization code:");
    System.out.println("  " + url);
    System.out.println("Enter authorization code:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String code = br.readLine();

    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

    // Create a new authorized API client
    Directory service = new Directory.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("DirectoryCommandLine")
        .build();

    List<User> allUsers = new ArrayList<User>();
    Directory.Users.List request = service.users().list().setCustomer("my_customer");

    // Get all users
    do {
      try {
        Users currentPage = request.execute();
        allUsers.addAll(currentPage.getUsers());
        request.setPageToken(currentPage.getNextPageToken());
      } catch (IOException e) {
        System.out.println("An error occurred: " + e);
        request.setPageToken(null);
      }
    } while (request.getPageToken() != null &&
             request.getPageToken().length() > 0 );

    // Print all users
    for (User currentUser : allUsers) {
      System.out.println(currentUser.getPrimaryEmail());
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您确实需要使用浏览器来获取用户的授权,但如果您安全地存储刷新令牌,则只需要执行一次。 你的情景是什么?您可以在移动设备中使用嵌入式浏览器,并自动获取授权码。