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

前端 未结 3 505
旧时难觅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:27

    Change your redirect_uri to your localhost page or project page.The request at the provided link will have your code sent. Request will have code="yourauthcode" in its url. Example: https://yourwebsite.com/yourpage.htm?code="yourauthcode"

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-01 10:41

    The command line samples were written for simplicity, not necessarily the best user experience. In this case, they're running as local apps and are using the installed app flow for OAuth 2.0. That flow does have a mode where the redirect_uri can point to localhost, but it requires starting up a temporary web server to receive the redirect. Rather than complicate the sample, it uses the OOB mode which requires copy/pasting the code.

    If you're building a desktop app, I'd encourage going the route of redirecting to localhost as it is a better UX.

    See https://developers.google.com/accounts/docs/OAuth2InstalledApp for more info.

    0 讨论(0)
提交回复
热议问题