针对Web应用程序的Google驱动器持久身份验证

时间:2017-05-22 10:01:09

标签: java oauth-2.0 google-drive-api google-oauth

我使用Oauth2.0和驱动器v2 API处理谷歌驱动器身份验证。我在google app console中为我新创建的应用程序提供了clientId,客户端密码和重定向URI。我尝试使用这些clientID和客户端密钥对驱动器进行身份验证。 这是我用于通过谷歌驱动器进行身份验证并从中获取文件的代码。

    public class GoolgeDriveUpload3 {

    private static String CLIENT_ID = "xxxxxxxxxx";
    private static String CLIENT_SECRET = "yyyyyyyyyy";
    static HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    static JsonFactory jsonFactory = new JacksonFactory();
    private static FileDataStoreFactory DATA_STORE_FACTORY;

    private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
            ".credentials/drive-java-quickstart");

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }

    public static void main(String[] args) throws IOException {
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, jsonFactory,
                CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE_FILE)).setDataStoreFactory(DATA_STORE_FACTORY)
                        .setAccessType("online").setApprovalPrompt("auto").build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalCallbackServer()).authorize("user");
        Drive service = new Drive.Builder(HTTP_TRANSPORT, jsonFactory, credential).build();
        List<File> result = new ArrayList<File>();
        Files.List request = null;
        request = service.files().list();
        FileList files = request.setQ("'root' in parents and trashed=false  ").execute();
        result.addAll(files.getItems());
        request.setPageToken(files.getNextPageToken());

        for (File f : result) {
            System.out.println("Files are: " + f.getTitle() + " " + f.getId() + " " + f.getAlternateLink());
        }
     }
  }

public class LocalCallbackServer implements VerificationCodeReceiver {

    volatile String code;
    private final int LOCAL_SERVER_PORT = 9058;

    @Override
    public synchronized String waitForCode() {

        try {
            this.wait();
        } catch (Exception ex) {
        }
        System.out.println("returning code is -> " + code);
        return code;

    }

    @Override
    public String getRedirectUri() {

        new Thread(new MyThread()).start();
        return "http://127.0.0.1:" + LOCAL_SERVER_PORT;
    }

    @Override
    public void stop() {
    }

    class MyThread implements Runnable {

        @Override
        public void run() {
            try {
                // return GoogleOAuthConstants.OOB_REDIRECT_URI;
                ServerSocket ss = new ServerSocket(LOCAL_SERVER_PORT);
                System.out.println("server is ready...");
                Socket socket = ss.accept();
                System.out.println("new request....");
                InputStream is = socket.getInputStream();
                StringWriter writer = new StringWriter();
                String firstLine = null;

                InputStreamReader isr = new InputStreamReader(is);
                StringBuilder sb = new StringBuilder();
                BufferedReader br = new BufferedReader(isr);
                String read = br.readLine();
                firstLine = read;
                OutputStream os = socket.getOutputStream();
                PrintWriter out = new PrintWriter(os, true);

                StringTokenizer st = new StringTokenizer(firstLine, " ");
                st.nextToken();
                String codeLine = st.nextToken();
                st = new StringTokenizer(codeLine, "=");
                st.nextToken();
                code = st.nextToken();

                out.write("RETURNED CODE IS " + code + "");
                out.flush();
                // is.close();

                socket.close();

                System.out.println("Extracted coded is " + code);

                synchronized (LocalCallbackServer.this) {
                    LocalCallbackServer.this.notify();
                }
                System.out.println("return is " + sb.toString());

            } catch (IOException ex) {
                Logger.getLogger(LocalCallbackServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

当我运行此操作时,我在浏览器中获得了一个新窗口,其中包含我已指定的URI和允许访问的Google帐户权限。一旦身份验证完成,我将上传一些文件到驱动器。我希望这个身份验证是持久的,以便我可以在后台执行这些操作。但我认为每隔3600秒我就会有一个新的窗口允许访问。我有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

setAccessType更改为offline。这将导致访问令牌和刷新令牌。从理论上讲,库将自动使用RT来获取新的AT。

答案 1 :(得分:0)

您需要将Credential对象保存到本地存储,以便以后重复使用。如果使用access_type ='offline'(“{3}}”的“刷新访问令牌(离线访问)”部分,则凭据对象创建一天或无限制(使用刷新访问令牌)