List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newAuthorizationUrl
@Override
public GoogleAuthorizationCodeRequestUrl newAuthorizationUrl()
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);//www . j a va 2 s .co 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:de.quaddy_services.deadlinereminder.extern.OAuth2Native.java
License:Apache License
/** * Authorizes the installed application to access user's protected data. * //ww w . j a va 2 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(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 www . j a va2 s . co m*/ 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 w w w . ja va 2 s . c om*/ 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:gnomezgrave.gsyncj.auth.Authorization.java
public static String getAuthURL() { 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(); return flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build(); }
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 w w. j a v a 2s .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 String requestAccess(Iterable<String> scopes) { GoogleAuthorizationCodeFlow flow = startFlow(scopes); String build = flow.newAuthorizationUrl() .setRedirectUri(Iterables.getFirst(clientSecrets.getInstalled().getRedirectUris(), "")).build(); return build; }
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 . j a va 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:net.wasdev.gameon.auth.google.GoogleAuth.java
License:Apache License
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonFactory jsonFactory = new JacksonFactory(); HttpTransport httpTransport = new NetHttpTransport(); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(httpTransport, jsonFactory, key, secret, Arrays.asList("https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email")); try {/*from w ww . j a va 2 s. c o m*/ // google will tell the users browser to go to this address once // they are done authing. StringBuffer callbackURL = request.getRequestURL(); int index = callbackURL.lastIndexOf("/"); callbackURL.replace(index, callbackURL.length(), "").append("/GoogleCallback"); request.getSession().setAttribute("google", flow); String authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(callbackURL.toString()).build(); // send the user to google to be authenticated. response.sendRedirect(authorizationUrl); } catch (Exception e) { throw new ServletException(e); } }
From source file:org.dishevelled.variation.googlegenomics.GoogleGenomicsFactory.java
License:Open Source License
/** * Return the authorization URL for the specified Google Genomics API authorization code flow. * * @param googleAuthorizationCodeFlow Google Genomics API authorization code flow, must not be null * @return the authorization URL for the specified Google Genomics API authorization code flow *///from w w w . ja va 2 s. co m public String authorizationUrl(final GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow) { checkNotNull(googleAuthorizationCodeFlow); String authorizationUrl = googleAuthorizationCodeFlow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI) .build(); if (logger.isInfoEnabled()) { logger.info("created new google genomics authorization url {}", authorizationUrl); } return authorizationUrl; }