How to authenticate Google Drive without requiring the user to copy/paste auth code?

前端 未结 3 522
旧时难觅i
旧时难觅i 2021-02-01 09:44

I\'m playing around with the DriveCommandLine applicaiton to learn the Drive API a bit. I\'m just wondering if it is possible to authenticate my desktop application with Google

3条回答
  •  再見小時候
    2021-02-01 10:38

    Step 1: Generate the URL using offline access type

    flow = new GoogleAuthorizationCodeFlow.Builder(
    httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
    .setAccessType("offline")
    .setApprovalPrompt("auto").build();
    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
    

    Step 2: Store the credentials accessToken and refreshToken

    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
                GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                    .setJsonFactory(jsonFactory)
                    .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
                    .build()
                    .setFromTokenResponse(response);
    String accessToken = credential.getAccessToken();
    String refreshToken = credential.getRefreshToken();
    

    Step 3: Reuse tokens when needed

    GoogleCredential credential1 = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
    .setTransport(httpTransport).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build();
    credential1.setAccessToken(accessToken);
    credential1.setRefreshToken(refreshToken);
    Drive service = new Drive.Builder(httpTransport, jsonFactory, credential1).build();
    

    Step 4: Understand OAuth to handle errors and refreshing of the tokens

提交回复
热议问题