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.twasyl.slideshowfx.hosting.connector.drive.DriveHostingConnector.java

License:Apache License

@Override
public boolean authenticate() {

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

    final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            GlobalConfiguration.getProperty(this.CONSUMER_KEY),
            GlobalConfiguration.getProperty(this.CONSUMER_SECRET), Arrays.asList(DriveScopes.DRIVE))
                    .setAccessType("online").setApprovalPrompt("auto").build();

    final WebView browser = new WebView();
    final Scene scene = new Scene(browser);
    final Stage stage = new Stage();

    browser.setPrefSize(500, 500);/*from  w w w.  ja  va  2  s.c o m*/
    browser.getEngine().getLoadWorker().stateProperty().addListener((stateValue, oldState, newState) -> {
        if (newState == Worker.State.SUCCEEDED) {

            final HTMLInputElement codeElement = (HTMLInputElement) browser.getEngine().getDocument()
                    .getElementById("code");
            if (codeElement != null) {
                final String authorizationCode = codeElement.getValue();

                try {
                    final GoogleTokenResponse response = flow.newTokenRequest(authorizationCode.toString())
                            .setRedirectUri(GlobalConfiguration.getProperty(this.REDIRECT_URI)).execute();

                    this.credential = new GoogleCredential().setFromTokenResponse(response);
                    this.accessToken = this.credential.getAccessToken();
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to get access token", e);
                    this.accessToken = null;
                } finally {
                    GlobalConfiguration.setProperty(this.ACCESS_TOKEN, this.accessToken);
                    stage.close();
                }

            }
        }
    });
    browser.getEngine().load(flow.newAuthorizationUrl()
            .setRedirectUri(GlobalConfiguration.getProperty(this.REDIRECT_URI)).build());

    stage.setScene(scene);
    stage.setTitle("Authorize SlideshowFX in Google Drive");
    stage.showAndWait();

    return this.isAuthenticated();
}

From source file:custom.application.login.java

License:Apache License

public String oAuth2callback() throws ApplicationException {
    HttpServletRequest request = (HttpServletRequest) this.context.getAttribute("HTTP_REQUEST");
    HttpServletResponse response = (HttpServletResponse) this.context.getAttribute("HTTP_RESPONSE");
    Reforward reforward = new Reforward(request, response);
    TokenResponse oauth2_response;/*from   w  w w. ja  v a  2 s. c  o m*/

    try {
        if (this.getVariable("google_client_secrets") == null) {
            clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                    new InputStreamReader(login.class.getResourceAsStream("/clients_secrets.json")));
            if (clientSecrets.getDetails().getClientId().startsWith("Enter")
                    || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
                System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/ ");
            }

            this.setVariable(new ObjectVariable("google_client_secrets", clientSecrets));
        } else
            clientSecrets = (GoogleClientSecrets) this.getVariable("google_client_secrets").getValue();

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES).build();

        oauth2_response = flow.newTokenRequest(request.getParameter("code"))
                .setRedirectUri(this.getLink("oauth2callback")).execute();

        System.out.println("Ok:" + oauth2_response.toPrettyString());
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        throw new ApplicationException(e1.getMessage(), e1);
    } catch (GeneralSecurityException e) {
        // TODO Auto-generated catch block
        throw new ApplicationException(e.getMessage(), e);
    }

    try {
        HttpClient httpClient = new DefaultHttpClient();
        String url = "https://www.google.com/m8/feeds/contacts/default/full";
        url = "https://www.googleapis.com/oauth2/v1/userinfo";
        HttpGet httpget = new HttpGet(url + "?access_token=" + oauth2_response.getAccessToken());
        httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");

        HttpResponse http_response = httpClient.execute(httpget);
        HeaderIterator iterator = http_response.headerIterator();
        while (iterator.hasNext()) {
            Header next = iterator.nextHeader();
            System.out.println(next.getName() + ":" + next.getValue());
        }

        InputStream instream = http_response.getEntity().getContent();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];

        int len;
        while ((len = instream.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }
        instream.close();
        out.close();

        Struct struct = new Builder();
        struct.parse(new String(out.toByteArray(), "utf-8"));

        this.usr = new User();
        this.usr.setEmail(struct.toData().getFieldInfo("email").stringValue());

        if (this.usr.findOneByKey("email", this.usr.getEmail()).size() == 0) {
            usr.setPassword("");
            usr.setUsername(usr.getEmail());

            usr.setLastloginIP(request.getRemoteAddr());
            usr.setLastloginTime(new Date());
            usr.setRegistrationTime(new Date());
            usr.append();
        }

        new passport(request, response, "waslogined").setLoginAsUser(this.usr.getId());

        reforward.setDefault(URLDecoder.decode(this.getVariable("from").getValue().toString(), "utf8"));
        reforward.forward();

        return new String(out.toByteArray(), "utf-8");
    } catch (ClientProtocolException e) {
        throw new ApplicationException(e.getMessage(), e);
    } catch (IOException e) {
        throw new ApplicationException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new ApplicationException(e.getMessage(), e);
    }

}

From source file:de.quaddy_services.deadlinereminder.extern.OAuth2Native.java

License:Apache License

/**
 * Authorizes the installed application to access user's protected data.
 * /*from w  ww.java2s  .  c o m*/
 * @param transport
 *            HTTP transport
 * @param jsonFactory
 *            JSON factory
 * @param receiver
 *            verification code receiver
 * @param scopes
 *            OAuth 2.0 scopes
 */
public static Credential authorize(HttpTransport transport, JsonFactory jsonFactory,
        VerificationCodeReceiver receiver, Iterable<String> scopes) throws Exception {
    String redirectUri = receiver.getRedirectUri();
    GoogleClientSecrets clientSecrets = loadClientSecrets(jsonFactory);
    // redirect to an authorization page
    GoogleAuthorizationCodeFlow.Builder tempBuilder = new GoogleAuthorizationCodeFlow.Builder(transport,
            jsonFactory, clientSecrets, scopes);
    tempBuilder.setCredentialStore(new PersistentCredentialStore());
    GoogleAuthorizationCodeFlow flow = tempBuilder.build();
    String tempUserName = System.getProperty("user.name", "-");
    Credential tempLoadCredential = flow.loadCredential(tempUserName);
    if (tempLoadCredential != null) {
        return tempLoadCredential;
    }
    browse(flow.newAuthorizationUrl().setRedirectUri(redirectUri).build());
    // receive authorization code and exchange it for an access token
    String code = receiver.waitForCode();
    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
    // store credential and return it
    Credential tempCreateAndStoreCredential = flow.createAndStoreCredential(response, tempUserName);
    receiver.stop();
    return tempCreateAndStoreCredential;
}

From source file:dfp.axis.other.OAuth2Example.java

License:Open Source License

private static Credential getOAuth2Credential() throws Exception {
    GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
            new NetHttpTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET, Lists.newArrayList(SCOPE))
                    .setApprovalPrompt("force")
                    // Set the access type to offline so that the token can be refreshed.
                    // By default, the library will automatically refresh tokens when it
                    // can, but this can be turned off by setting
                    // dfp.api.refreshOAuth2Token=false in your ads.properties file.
                    .setAccessType("offline").build();

    String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
    System.out.println("Paste this url in your browser: \n" + authorizeUrl + '\n');

    // Wait for the authorization code.
    System.out.println("Type the code you received here: ");
    String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

    // Authorize the OAuth2 token.
    GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationFlow.newTokenRequest(authorizationCode);
    tokenRequest.setRedirectUri(CALLBACK_URL);
    GoogleTokenResponse tokenResponse = tokenRequest.execute();

    // Create the OAuth2 credential with custom refresh listener.
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
            .setJsonFactory(new JacksonFactory()).setClientSecrets(CLIENT_ID, CLIENT_SECRET)
            .addRefreshListener(new CredentialRefreshListener() {
                public void onTokenResponse(Credential credential, TokenResponse tokenResponse) {
                    // Handle success.
                    System.out.println("Credential was refreshed successfully.");
                }/*from   w  ww .j  a v a 2 s.c  om*/

                public void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse) {
                    // Handle error.
                    System.err.println("Credential was not refreshed successfully. "
                            + "Redirect to error page or login screen.");
                }
            })

            // You can also add a credential store listener to have credentials
            // stored automatically.
            //.addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore))
            .build();

    // Set authorized credentials.
    credential.setFromTokenResponse(tokenResponse);

    // Though not necessary when first created, you can manually refresh the
    // token, which is needed after 60 minutes.
    credential.refreshToken();

    return credential;
}

From source file:gnomezgrave.gsyncj.auth.Authorization.java

public static synchronized Drive getDrive(String key) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE)).setAccessType("online")
                    .setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
    System.out.println(url);//from  www .ja v a  2s  .  com

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

    //Create a new authorized API client
    return new Drive.Builder(httpTransport, jsonFactory, credential).build();
}

From source file:guestbook.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.initializeFlow();

    //if null then authorization was denied
    if (req.getParameter("code") == null) {
        resp.sendRedirect("/settings.jsp");
        return;//from w  w w  .j av  a  2  s. c  o  m
    }
    // 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:javamailclient.GmailAPI.java

public static void initialize(String code) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));

    // Allow user to authorize via url.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            clientSecrets, Arrays.asList(SCOPE)).setAccessType("online").setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build();
    //System.out.println("Please open the following URL in your browser then type"+" the authorization code:\n" + url);

    // Read code entered by user.
    //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    //String code = br.readLine();

    // Generate Credential using retrieved code.
    GoogleTokenResponse response = flow.newTokenRequest(code)
            .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

    // Create a new authorized Gmail API client
    service = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName(APP_NAME).build();

    Profile profile = service.users().getProfile(USER).execute();
    USER_EMAIL = profile.getEmailAddress();
    System.out.println(USER_EMAIL);
    /*ListThreadsResponse threadsResponse = service.users().threads().list(USER).execute();
    List<Thread> threads = threadsResponse.getThreads();
            // w ww .j a  v a2 s.  c om
    // Print ID of each Thread.
    for (Thread thread : threads) {
      System.out.println("Thread ID: " + thread.getId());
    }*/
}

From source file:me.emily.oauth2.OAuth2Native.java

License:Apache License

public Credential authorize(String code, Iterable<String> scopes) throws IOException {

    GoogleAuthorizationCodeFlow flow = startFlow(scopes);

    GoogleTokenResponse response = flow.newTokenRequest(code)
            .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();

    log.info("/------------ Response ");
    log.info("|  Id: {}", response.getIdToken());
    log.info("|  Token: {}", response.getAccessToken());
    log.info("|  Refresh token: {}", response.getRefreshToken());
    log.info("|  Expiry: {}", response.getExpiresInSeconds());
    log.info("|  Type: {}", response.getTokenType());
    log.info("|  Scope: {}", response.getScope());
    for (Map.Entry<String, Object> entry : response.getUnknownKeys().entrySet()) {
        log.info("|  {}: {}", entry.getKey(), entry.getValue());
    }/*  ww w  .  j  a  va 2s .c o  m*/
    log.info("\\------------");

    Credential creds = flow.createAndStoreCredential(response, null);

    return creds;
}

From source file:net.nharyes.drivecopy.biz.wfm.TokenWorkflowManagerImpl.java

License:Apache License

private TokenBO get(TokenBO token) throws WorkflowManagerException {

    try {/*from  w  w  w. ja  v  a 2s .  c  o m*/

        // check client ID and client secret configuration existence
        if (!config.containsKey(CLIENT_ID_KEY) || !config.containsKey(CLIENT_SECRET_KEY)) {

            // request client data to user
            System.out.println("Configuration file not found; generating a new one...");
            System.out.println("(see https://github.com/Gherynos/DriveCopy/wiki/Setup for help)");
            System.out.println();
            System.out.println("Please insert CLIENT ID:");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String clientId = br.readLine();
            System.out.println("Please insert CLIENT SECRET:");
            String clientSecret = br.readLine();

            // store client data
            config.setProperty(CLIENT_ID_KEY, clientId);
            config.setProperty(CLIENT_SECRET_KEY, clientSecret);
            config.save();
        }

        // check tokens configuration existence
        if (!config.containsKey(ACCESS_TOKEN_KEY) || !config.containsKey(REFRESH_TOKEN_KEY)) {

            // request authorization to user
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
                    jsonFactory, config.getString(CLIENT_ID_KEY), config.getString(CLIENT_SECRET_KEY),
                    Arrays.asList(DriveScopes.DRIVE)).build();
            String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
            System.out
                    .println("Please open the following URL in your browser then type the authorization code:");
            System.out.println("  " + url);
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String code = br.readLine();

            // process response
            GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
            Credential credential = flow.createAndStoreCredential(response, null);

            // store tokens
            config.setProperty(ACCESS_TOKEN_KEY, credential.getAccessToken());
            config.setProperty(REFRESH_TOKEN_KEY, credential.getRefreshToken());
            config.save();
        }

        // return token
        return new TokenBO(config.getString(CLIENT_ID_KEY), config.getString(CLIENT_SECRET_KEY),
                config.getString(ACCESS_TOKEN_KEY), config.getString(REFRESH_TOKEN_KEY));

    } catch (IOException ex) {

        // re-throw exception
        throw new WorkflowManagerException(ex.getMessage(), ex);

    } catch (ConfigurationException ex) {

        // re-throw exception
        throw new WorkflowManagerException(ex.getMessage(), ex);
    }
}

From source file:org.dishevelled.variation.googlegenomics.GoogleGenomicsFactory.java

License:Open Source License

Genomics createGenomics(final GenomicsKey genomicsKey) throws IOException {
    final String rootUrl = genomicsKey.rootUrl();
    final String authorizationCode = genomicsKey.authorizationCode();
    final GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = genomicsKey.googleAuthorizationCodeFlow();
    if (logger.isInfoEnabled()) {
        logger.info("creating new google genomics api for root url {} authorization code {}", rootUrl,
                abbrev(authorizationCode));
    }/*from w ww . ja v  a 2  s  .  co  m*/
    TokenResponse tokenResponse = googleAuthorizationCodeFlow.newTokenRequest(authorizationCode)
            .setRedirectUri(REDIRECT_URI).execute();
    if (logger.isInfoEnabled()) {
        logger.info("received token response {}", abbrev(tokenResponse.getAccessToken()));
    }
    final Credential credential = googleAuthorizationCodeFlow.createAndStoreCredential(tokenResponse, "user");
    if (logger.isInfoEnabled()) {
        logger.info("received credential {} expires in {} s", abbrev(credential.getAccessToken()),
                credential.getExpiresInSeconds());
    }
    Genomics genomics = new Genomics.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME).setRootUrl(rootUrl).setServicePath("/")
            .setHttpRequestInitializer(new HttpRequestInitializer() {
                @Override
                public void initialize(final HttpRequest httpRequest) throws IOException {
                    credential.initialize(httpRequest);
                    httpRequest.setReadTimeout(60000); // 60 seconds                                                                                            
                }
            }).build();

    if (logger.isInfoEnabled()) {
        logger.info("created new google genomics api for root URL {} authorization code {} application name {}",
                rootUrl, abbrev(authorizationCode),
                genomics.getApplicationName() == null ? "null" : genomics.getApplicationName());
    }
    return genomics;
}