Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newTokenRequest

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newTokenRequest

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newTokenRequest.

Prototype

@Override
    public GoogleAuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) 

Source Link

Usage

From source file:com.google.cloud.bigquery.samples.BigQueryJavaGettingStarted.java

License:Apache License

/**
 * Exchange the authorization code for OAuth 2.0 credentials.
 *
 * @return an authorized Google Auth flow
 *//*from  w  w w.j ava 2s  .c om*/
static Credential exchangeCode(String authorizationCode) throws IOException {
    GoogleAuthorizationCodeFlow flow = getFlow();
    GoogleTokenResponse response = flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI)
            .execute();
    return flow.createAndStoreCredential(response, null);
}

From source file:com.letscode.rsync.Main.java

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    if (args.length <= 0) {
        System.out.println("Please input your upload file path : ");
        filePath = br.readLine();/*from  w  w  w .ja v  a  2s.  co  m*/
        if ("".equals(filePath)) {
            System.exit(0);
        }
    } else {
        filePath = args[0];
    }

    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            CLIENT_ID, CLIENT_SECRET, Arrays.asList(new String[] { "https://www.googleapis.com/auth/drive" }))
                    .setAccessType("online").setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri("urn:ietf:wg:oauth:2.0:oob").build();
    System.out.println("****Please open the following URL in your browser then type the authorization code");
    System.out.println("[COPY] " + url);
    System.out.print("[PASTE] Authen code : ");
    String code = br.readLine();

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

    drive = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName(APPLICATION_NAME)
            .build();

    uploadFolder(false, filePath);
}

From source file:com.liferay.google.GoogleOAuth.java

License:Open Source License

protected Credential exchangeCode(long companyId, String authorizationCode, String redirectUri)
        throws CodeExchangeException, SystemException {

    try {/*from w ww .ja  va2 s  .  c o m*/
        GoogleAuthorizationCodeFlow flow = getFlow(companyId);

        GoogleAuthorizationCodeTokenRequest token = flow.newTokenRequest(authorizationCode);

        token.setRedirectUri(redirectUri);

        GoogleTokenResponse response = token.execute();

        return flow.createAndStoreCredential(response, null);
    } catch (IOException e) {
        System.err.println("An error occurred: " + e);

        throw new CodeExchangeException();
    }
}

From source file:com.liferay.google.login.hook.action.GoogleLoginAction.java

License:Open Source License

protected Credential getCredential(long companyId, String authorizationCode, String redirectURI)
        throws Exception {

    GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = getGoogleAuthorizationCodeFlow(companyId);

    GoogleAuthorizationCodeTokenRequest googleAuthorizationCodeTokenRequest = googleAuthorizationCodeFlow
            .newTokenRequest(authorizationCode);

    googleAuthorizationCodeTokenRequest.setRedirectUri(redirectURI);

    GoogleTokenResponse googleTokenResponse = googleAuthorizationCodeTokenRequest.execute();

    return googleAuthorizationCodeFlow.createAndStoreCredential(googleTokenResponse, null);
}

From source file:com.liferay.portal.security.sso.google.internal.GoogleAuthorizationImpl.java

License:Open Source License

@Override
public User addOrUpdateUser(HttpSession session, long companyId, String authorizationCode,
        String returnRequestUri, List<String> scopes) throws Exception {

    GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = getGoogleAuthorizationCodeFlow(companyId, scopes);

    GoogleAuthorizationCodeTokenRequest googleAuthorizationCodeTokenRequest = googleAuthorizationCodeFlow
            .newTokenRequest(authorizationCode);

    googleAuthorizationCodeTokenRequest.setRedirectUri(returnRequestUri);

    GoogleTokenResponse googleTokenResponse = googleAuthorizationCodeTokenRequest.execute();

    Credential credential = googleAuthorizationCodeFlow.createAndStoreCredential(googleTokenResponse, null);

    Userinfoplus userinfoplus = getUserinfoplus(credential);

    if (userinfoplus == null) {
        return null;
    }// ww  w. j a  v a  2  s  .c  o  m

    ServiceBeanMethodInvocationFactoryUtil.proceed(this, GoogleAuthorizationImpl.class, _doAddOrUpdateUser,
            new Object[] { session, companyId, userinfoplus }, new String[] { "transactionAdvice" });

    return doAddOrUpdateUser(session, companyId, userinfoplus);
}

From source file:com.mkyong.controller.PlusSampleAuthCallbackServlet.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // Note that this implementation does not handle the user denying authorization.
    GoogleAuthorizationCodeFlow authFlow = Utils.initializeFlowCalendar();
    // Exchange authorization code for user credentials.
    GoogleTokenResponse tokenResponse = authFlow.newTokenRequest(req.getParameter("code"))
            .setRedirectUri(Utils.getRedirectUri(req)).execute();
    // Save the credentials for this user so we can access them from the main servlet.
    authFlow.createAndStoreCredential(tokenResponse, Utils.getUserId(req));

    resp.sendRedirect(Utils.MAIN_SERVLET_PATH);
}

From source file:com.niroshpg.android.gmail.PlusSampleAuthCallbackServlet.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // Note that this implementation does not handle the user denying authorization.
    GoogleAuthorizationCodeFlow authFlow = GmailUtils.newFlow();
    // Exchange authorization code for user credentials.
    GoogleTokenResponse tokenResponse = authFlow.newTokenRequest(req.getParameter("code"))
            .setRedirectUri(GmailUtils.getRedirectUri(req)).execute();
    // Save the credentials for this user so we can access them from the main servlet.
    authFlow.createAndStoreCredential(tokenResponse, GmailUtils.getUserId(req));
    resp.sendRedirect(GmailUtils.MAIN_SERVLET_PATH);
}

From source file:com.NSSWare.MultiSync.GoogleDriveSyncer.java

@Override
public void finishOAuth2(String accessToken)
        throws SyncerException, SyncerException.NetworkException, SyncerException.BadRequestException {

    try {//w  w w.  j  a  va  2s.c  o  m
        List<String> useScope = getScope();

        GoogleAuthorizationCodeFlow flow = getFlow(useScope);
        GoogleTokenResponse response = flow.newTokenRequest(accessToken).setRedirectUri(REDIRECT_URI).execute();
        Credential cred = flow.createAndStoreCredential(response, null);

        accessToken = cred.getAccessToken();

        service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, cred).setApplicationName("Test").build();

    } catch (com.google.api.client.auth.oauth2.TokenResponseException e1) {
        //If this happens, you most likely have the wrong key
        throw new SyncerException.BadRequestException(e1.getMessage(), e1.getCause());
    } catch (IOException e2) {
        //If this happens, there is something wrong with the network somewhere along the line
        throw new SyncerException.NetworkException(e2.getMessage(), e2.getCause());
    } catch (Exception e3) {
        throw new SyncerException(e3.getMessage(), e3.getCause());
    }
}

From source file:com.otway.picasasync.webclient.GoogleOAuth.java

License:Apache License

public PicasawebClient authenticatePicasa(Settings settings, boolean allowInteractive, SyncState state)
        throws IOException, GeneralSecurityException {
    final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    log.info("Preparing to authenticate via OAuth...");
    Credential cred = null;// w ww  .j  av a2  s .  c om

    String refreshToken = settings.getRefreshToken();
    if (refreshToken != null) {
        // We have a refresh token - so get some refreshed credentials
        cred = getRefreshedCredentials(refreshToken);
    }

    if (cred == null && allowInteractive) {

        // Either there was no valid refresh token, or the credentials could not
        // be created (they may have been revoked). So run the auth flow

        log.info("No credentials - beginning OAuth flow...");

        state.setStatus("Requesting Google Authentication...");

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(httpTransport, jsonFactory, clientId,
                clientSecret, Collections.singleton(scope));

        String authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUrl)
                .setAccessType("offline").setApprovalPrompt("force").build();

        try {
            OAuthGUI authGUI = new OAuthGUI();

            // Display the interactive GUI for the user to log in via the browser
            String code = authGUI.initAndShowGUI(authorizationUrl, state);

            log.info("Token received from UI. Requesting credentials...");

            // Now we have the code from the interactive login, set up the
            // credentials request and call it.
            GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUrl).execute();

            // Retrieve the credential from the request response
            cred = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
                    .setClientSecrets(clientId, clientSecret).build().setFromTokenResponse(response);

            state.setStatus("Google Authentication succeeded.");

            log.info("Credentials received - storing refresh token...");

            // Squirrel this away for next time
            settings.setRefreshToken(cred.getRefreshToken());
            settings.saveSettings();
        } catch (Exception ex) {
            log.error("Failed to initialise interactive OAuth GUI", ex);
        }
    }

    if (cred != null) {

        log.info("Building PicasaWeb Client...");

        // Build a web client using the credentials we created
        return new PicasawebClient(cred);
    }

    return null;
}

From source file:com.singhanuvrat.experiment.googleapi.OAuth2Native.java

License:Apache License

/**
 * Authorizes the installed application to access user's protected data.
 * /*  ww w.j a va2  s. c  om*/
 * @param transport HTTP transport
 * @param jsonFactory JSON factory
 * @param receiver verification code receiver
 * @param scopes OAuth 2.0 scopes
 */
public static Credential authorize(final HttpTransport transport, final JsonFactory jsonFactory,
        final VerificationCodeReceiver receiver, final Iterable<String> scopes) throws Exception {
    try {
        final String redirectUri = receiver.getRedirectUri();
        final GoogleClientSecrets clientSecrets = OAuth2Native.loadClientSecrets(jsonFactory);
        // redirect to an authorization page
        // TODO(mlinder, 1.11.0-beta): Use setAccessType("offline").setApprovalPrompt("force") with
        // FileCredentialStore.
        final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory,
                clientSecrets, scopes).setAccessType("offline").setApprovalPrompt("force").build();
        OAuth2Native.browse(flow.newAuthorizationUrl().setRedirectUri(redirectUri).build());
        // receive authorization code and exchange it for an access token
        final String code = receiver.waitForCode();
        final GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
        // store credential and return it
        return flow.createAndStoreCredential(response, null);
    } finally {
        receiver.stop();
    }
}