Search code examples
javaoauth-2.0google-drive-apigoogle-oauth

Google drive persistant authentication for a web application


I'm working with google drive authentication using Oauth2.0 and drive v2 API. I have got clientId , client secret and redirect URI for my newly created application in google app console.I'm trying to autheticate with drive using these clientID and client secret. Here is the code which I used for authenticating with google drive and getting the files from it.

    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);
            }
        }
    }
}

When i run this i get a new window in the browser with URI i have specified and google account permission to allow the access. Once the Authentication is done I will be uploading some files to drive .I want this aunthentication to be persistant so that i can perform these actions in the background. But I think every 3600 sec I'm getting a new window to allow the access.Is there any way i can fix this issue?


Solution

  • change setAccessType to offline. This will result in both an Access Token and a Refresh Token. In theory, the library will automatically use the RT to fetch new AT's as it needs them.