com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse Java Examples
The following examples show how to use
com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AdvancedCreateCredentialFromScratch.java From googleads-java-lib with Apache License 2.0 | 6 votes |
private static void authorize(DataStoreFactory storeFactory, String userId) throws Exception { // Depending on your application, there may be more appropriate ways of // performing the authorization flow (such as on a servlet), see // https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#authorization_code_flow // for more information. GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder( new NetHttpTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET, Arrays.asList(SCOPE)) .setDataStoreFactory(storeFactory) // 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 // api.adwords.refreshOAuth2Token=false in your ads.properties file. .setAccessType("offline").build(); String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build(); System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl); // Wait for the authorization code. System.out.println("Type the code you received here: "); @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate. 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(); // Store the credential for the user. authorizationFlow.createAndStoreCredential(tokenResponse, userId); }
Example #2
Source File: AdvancedCreateCredentialFromScratch.java From googleads-java-lib with Apache License 2.0 | 6 votes |
private static void authorize(DataStoreFactory storeFactory, String userId) throws Exception { // Depending on your application, there may be more appropriate ways of // performing the authorization flow (such as on a servlet), see // https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#authorization_code_flow // for more information. GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder( new NetHttpTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET, Arrays.asList(SCOPE)) .setDataStoreFactory(storeFactory) // 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 // api.admanager.refreshOAuth2Token=false in your ads.properties file. .setAccessType("offline") .build(); String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build(); System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl); // Wait for the authorization code. System.out.println("Type the code you received here: "); @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate. 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(); // Store the credential for the user. authorizationFlow.createAndStoreCredential(tokenResponse, userId); }
Example #3
Source File: CredentialManager.java From drivemarks with Apache License 2.0 | 6 votes |
/** * Retrieves a new access token by exchanging the given code with OAuth2 * end-points. * @param code Exchange code. * @return A credential object. */ public Credential retrieve(String code) { try { GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest( transport, jsonFactory, clientSecrets.getWeb().getClientId(), clientSecrets.getWeb().getClientSecret(), code, clientSecrets.getWeb().getRedirectUris().get(0)).execute(); return buildEmpty().setAccessToken(response.getAccessToken()); } catch (IOException e) { new RuntimeException("An unknown problem occured while retrieving token"); } return null; }
Example #4
Source File: GuiMain.java From google-sites-liberation with Apache License 2.0 | 6 votes |
/** * Retrieve OAuth 2.0 credentials. * * @return OAuth 2.0 Credential instance. * @throws IOException */ private Credential getCredentials() throws IOException { String code = tokenField.getText(); HttpTransport transport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); String CLIENT_SECRET = "EPME5fbwiNLCcMsnj3jVoXeY"; // Step 2: Exchange --> GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest( transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, code, REDIRECT_URI).execute(); // End of Step 2 <-- // Build a new GoogleCredential instance and return it. return new GoogleCredential.Builder() .setClientSecrets(CLIENT_ID, CLIENT_SECRET) .setJsonFactory(jsonFactory).setTransport(transport).build() .setAccessToken(response.getAccessToken()) .setRefreshToken(response.getRefreshToken()); }
Example #5
Source File: ReportsFeature.java From appengine-tck with Apache License 2.0 | 6 votes |
protected void handleTokens(Map<String, String> params) { final GoogleClientSecrets secrets = new GoogleClientSecrets().setInstalled( new GoogleClientSecrets.Details(). setClientId(params.get(constants.getApplicationClientId())). setClientSecret(params.get(constants.getApplicationClientSecret())) ); try { final GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest( this.httpTransport, this.jsonFactory, secrets.getDetails().getClientId(), secrets.getDetails().getClientSecret(), params.get(constants.getApplicationOauthCode()), constants.getRedirectUri() ).execute(); params.put(constants.getApplicationRefreshToken(), tokenResponse.getRefreshToken()); params.put(constants.getApplicationAccessToken(), tokenResponse.getAccessToken()); } catch (IOException e) { throw new RuntimeException(e); } }
Example #6
Source File: GoogleDriveServiceImpl.java From sakai with Educational Community License v2.0 | 5 votes |
public boolean token(String userId, String code) { if (!isConfigured()) { return false; } try { GoogleTokenResponse googleResponse = flow.newTokenRequest(code) .setRedirectUri(redirectUri) .execute(); Credential cred = flow.createAndStoreCredential(googleResponse, userId); service = new Drive.Builder(httpTransport, jsonFactory, cred) .setApplicationName(GOOGLEDRIVE_APP_NAME) .build(); Drive.About about = service.about(); Drive.About.Get get = about.get().setFields("user(displayName, emailAddress, permissionId)"); About ab = get.execute(); log.debug("About : {}", ab.toString()); GoogleDriveUser du = getGoogleDriveUser(userId); du.setGoogleDriveUserId(ab.getUser().getPermissionId()); du.setGoogleDriveName(ab.getUser().getEmailAddress()); googledriveRepo.update(du); return true; } catch(Exception e) { log.warn("GoogleDrive: Error while retrieving or saving the credentials for user {} : {}", userId, e.getMessage()); revokeGoogleDriveConfiguration(userId); } return false; }
Example #7
Source File: InstalledOAuth2Authenticator.java From aw-reporting with Apache License 2.0 | 5 votes |
private Credential getNewOAuth2Credential() throws OAuthException { GoogleAuthorizationCodeFlow authorizationFlow = getAuthorizationFlow(); String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build(); System.out.println("\n**ACTION REQUIRED** Paste this url in your browser" + " and authenticate using your **AdWords Admin Account**: \n\n" + authorizeUrl + '\n'); // Wait for the authorization code. System.out.println("Type the code you received on the web page here: "); try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) { String authorizationCode = reader.readLine(); // Authorize the OAuth2 token. GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationFlow.newTokenRequest(authorizationCode); tokenRequest.setRedirectUri(CALLBACK_URL); GoogleTokenResponse tokenResponse = tokenRequest.execute(); // Create the credential. Credential credential = new GoogleCredential.Builder() .setClientSecrets(clientId, clientSecret) .setJsonFactory(new JacksonFactory()) .setTransport(new NetHttpTransport()) .build() .setFromTokenResponse(tokenResponse); return credential; } catch (IOException e) { throw new OAuthException("An error occured obtaining the OAuth2Credential", e); } }
Example #8
Source File: GetRefreshTokenWithoutPropertiesFile.java From googleads-java-lib with Apache License 2.0 | 5 votes |
private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets) throws IOException { GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder( new NetHttpTransport(), new JacksonFactory(), clientSecrets, Arrays.asList(SCOPE)) // 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 // api.adwords.refreshOAuth2Token=false in your ads.properties file. .setAccessType("offline").build(); String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build(); System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl); // Wait for the authorization code. System.out.println("Type the code you received here: "); @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate. 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. GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .setClientSecrets(clientSecrets) .build(); // Set authorized credentials. credential.setFromTokenResponse(tokenResponse); return credential; }
Example #9
Source File: GetRefreshToken.java From googleads-java-lib with Apache License 2.0 | 5 votes |
private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets) throws IOException { GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder( new NetHttpTransport(), new JacksonFactory(), clientSecrets, SCOPES) // 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 // api.adwords.refreshOAuth2Token=false in your ads.properties file. .setAccessType("offline").build(); String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build(); System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl); // Wait for the authorization code. System.out.println("Type the code you received here: "); @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate. 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. GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .setClientSecrets(clientSecrets) .build(); // Set authorized credentials. credential.setFromTokenResponse(tokenResponse); return credential; }
Example #10
Source File: GetRefreshTokenWithoutPropertiesFile.java From googleads-java-lib with Apache License 2.0 | 5 votes |
private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets) throws Exception { GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder( new NetHttpTransport(), new JacksonFactory(), clientSecrets, Arrays.asList(SCOPE)) // 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 // api.admanager.refreshOAuth2Token=false in your ads.properties file. .setAccessType("offline").build(); String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build(); System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl); // Wait for the authorization code. System.out.println("Type the code you received here: "); @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate. 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. GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .setClientSecrets(clientSecrets) .build(); // Set authorized credentials. credential.setFromTokenResponse(tokenResponse); return credential; }
Example #11
Source File: GetRefreshToken.java From googleads-java-lib with Apache License 2.0 | 5 votes |
private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets) throws Exception { GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder( new NetHttpTransport(), new JacksonFactory(), clientSecrets, SCOPES) // 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 // api.admanager.refreshOAuth2Token=false in your ads.properties file. .setAccessType("offline").build(); String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build(); System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl); // Wait for the authorization code. System.out.println("Type the code you received here: "); @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate. 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. GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .setClientSecrets(clientSecrets) .build(); // Set authorized credentials. credential.setFromTokenResponse(tokenResponse); return credential; }
Example #12
Source File: GoogleDriveServiceImpl.java From sakai with Educational Community License v2.0 | 5 votes |
public boolean token(String userId, String code) { if (!isConfigured()) { return false; } try { GoogleTokenResponse googleResponse = flow.newTokenRequest(code) .setRedirectUri(redirectUri) .execute(); Credential cred = flow.createAndStoreCredential(googleResponse, userId); service = new Drive.Builder(httpTransport, jsonFactory, cred) .setApplicationName(GOOGLEDRIVE_APP_NAME) .build(); Drive.About about = service.about(); Drive.About.Get get = about.get().setFields("user(displayName, emailAddress, permissionId)"); About ab = get.execute(); log.debug("About : {}", ab.toString()); GoogleDriveUser du = getGoogleDriveUser(userId); du.setGoogleDriveUserId(ab.getUser().getPermissionId()); du.setGoogleDriveName(ab.getUser().getEmailAddress()); googledriveRepo.update(du); return true; } catch(Exception e) { log.warn("GoogleDrive: Error while retrieving or saving the credentials for user {} : {}", userId, e.getMessage()); revokeGoogleDriveConfiguration(userId); } return false; }
Example #13
Source File: CachingGoogleAuthCodeFlow.java From nexus-proxy with Apache License 2.0 | 5 votes |
/** * Returns the principal authenticated by {@code token}. * * @param token an instance of {@link GoogleTokenResponse}. * @return the principal authenticated by {@code token}. */ public final String getPrincipal(final GoogleTokenResponse token) { try { return token.parseIdToken().getPayload().getEmail(); } catch (final IOException ex) { throw new UncheckedIOException(ex); } }
Example #14
Source File: GoogleAuthorizationResponseServlet.java From spring-security-jwt with MIT License | 5 votes |
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check for a valid XSRF token String expectedToken = (String) request.getSession().getAttribute(XsrfUtils.XSRF_KEY); String actualToken = request.getParameter("state"); if (!xsrfUtils.isValid(expectedToken, actualToken)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } // Check for no errors in the OAuth process String[] error = request.getParameterValues(ERROR_URL_PARAM_NAME); if (error != null && error.length > 0) { response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); return; } // Check for the presence of the response code String[] code = request.getParameterValues(CODE_URL_PARAM_NAME); if (code == null || code.length == 0) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // Get the email address String requestUrl = getOAuthCodeCallbackHandlerUrl(request); GoogleTokenResponse tokenResponse = exchangeCodeForAccessAndRefreshTokens(code[0], requestUrl); String email = tokenResponse.parseIdToken().getPayload().getEmail(); String token = establishUserAndLogin(response, email); request.setAttribute("email", email); request.setAttribute("authToken", token); getServletConfig().getServletContext().getRequestDispatcher("/home.jsp").forward(request,response); }
Example #15
Source File: GoogleCallback.java From liberty-bikes with Eclipse Public License 1.0 | 5 votes |
@GET @Counted(name = "num_google_logins", displayName = "Number of Google Logins", description = "How many times a user has logged in through Google Auth.", absolute = true) public Response getGoogleAuthURL(@Context HttpServletRequest request) throws IOException, URISyntaxException { // google calls us back at this app when a user has finished authing with them. // when it calls us back here, it passes an oauth_verifier token that we // can exchange for a google access token. GoogleAuthorizationCodeFlow flow = (GoogleAuthorizationCodeFlow) request.getSession().getAttribute("google"); if (flow == null) return failureRedirect("did not find 'google' attribute set in HTTP session. It should be set by GoogleAuth"); String code = request.getParameter("code"); //now we need to invoke the access_token endpoint to swap the code for a token. String callbackURL = config.authUrl + "/GoogleCallback"; Map<String, String> claims = new HashMap<String, String>(); try { GoogleAuthorizationCodeTokenRequest token = flow.newTokenRequest(code).setRedirectUri(callbackURL); GoogleTokenResponse gResponse = token.execute(); claims.putAll(introspectAuth(flow, gResponse)); } catch (IOException e) { e.printStackTrace(); } // if auth key was no longer valid, we won't build a JWT. Redirect back to start. if (!"true".equals(claims.get("valid"))) { return failureRedirect("claim was not valid"); } else { String newJwt = createJwt(claims); return Response.temporaryRedirect(new URI(config.frontendUrl + "/" + newJwt)).build(); } }
Example #16
Source File: GoogleCallback.java From liberty-bikes with Eclipse Public License 1.0 | 5 votes |
/** * Method that performs introspection on an AUTH string, and returns data as * a String->String hashmap. * * @param auth * the authstring to query, as built by an auth impl. * @return the data from the introspect, in a map. */ private Map<String, String> introspectAuth(GoogleAuthorizationCodeFlow flow, GoogleTokenResponse gResponse) throws IOException { Map<String, String> results = new HashMap<String, String>(); Credential credential = flow.createAndStoreCredential(gResponse, null); try { // ask google to verify the response from the auth string // if invalid, it'll throw an exception HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(credential); GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v3/userinfo"); HttpRequest infoRequest = requestFactory.buildGetRequest(url); infoRequest.getHeaders().setContentType(MediaType.APPLICATION_JSON); String jsonIdentity = infoRequest.execute().parseAsString(); GoogleUser user = jsonb.fromJson(jsonIdentity, GoogleUser.class); System.out.println("User logged in: " + jsonb.toJson(user)); Objects.requireNonNull(user.name, "User name was null"); Objects.requireNonNull(user.email, "User email was null"); results.put("valid", "true"); results.put("id", "GOOGLE:" + user.email); results.put("upn", user.email); results.put("name", user.name); results.put("email", user.email); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); results.put("valid", "false"); } return results; }
Example #17
Source File: CachingGoogleAuthCodeFlow.java From nexus-proxy with Apache License 2.0 | 5 votes |
/** * Stores the credential corresponding to the specified {@link GoogleTokenResponse}. * * @param token an instance of {@link GoogleTokenResponse}. * @return the {@link Credential} corresponding to the specified {@link GoogleTokenResponse}. */ public final Credential storeCredential(final GoogleTokenResponse token) { try { return this.authFlow.createAndStoreCredential(token, this.getPrincipal(token)); } catch (final IOException ex) { throw new UncheckedIOException(ex); } }
Example #18
Source File: CachingGoogleAuthCodeFlow.java From nexus-proxy with Apache License 2.0 | 5 votes |
/** * Returns a {@link GoogleTokenResponse} corresponding to an authorization code token request based on the given * authorization code. * * @param authorizationCode the authorization code to use. * @return a {@link GoogleTokenResponse} corresponding to an auth code token request based on the given auth code. */ public final GoogleTokenResponse requestToken(final String authorizationCode) { try { return this.authFlow.newTokenRequest(authorizationCode).setRedirectUri(this.redirectUri).execute(); } catch (final IOException ex) { throw new UncheckedIOException(ex); } }
Example #19
Source File: Authorizer.java From mail-importer with Apache License 2.0 | 4 votes |
public Credential get() { try { GoogleClientSecrets clientSecrets = loadGoogleClientSecrets(jsonFactory); DataStore<StoredCredential> dataStore = getStoredCredentialDataStore(); // Allow user to authorize via url. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, clientSecrets, ImmutableList.of( GmailScopes.GMAIL_MODIFY, GmailScopes.GMAIL_READONLY)) .setCredentialDataStore(dataStore) .setAccessType("offline") .setApprovalPrompt("auto") .build(); // First, see if we have a stored credential for the user. Credential credential = flow.loadCredential(user.getEmailAddress()); // If we don't, prompt them to get one. if (credential == null) { 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. System.out.print("Code: "); System.out.flush(); 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(); credential = flow.createAndStoreCredential(response, user.getEmailAddress()); } Gmail gmail = new Gmail.Builder(httpTransport, jsonFactory, credential) .setApplicationName(GmailServiceModule.APP_NAME) .build(); Profile profile = gmail.users() .getProfile(user.getEmailAddress()) .execute(); System.out.println(profile.toPrettyString()); return credential; } catch (IOException exception) { throw new RuntimeException(exception); } }
Example #20
Source File: GoogleAuthorizationResponseServlet.java From spring-security-jwt with MIT License | 4 votes |
private GoogleTokenResponse exchangeCodeForAccessAndRefreshTokens(String code, String currentUrl) throws IOException { return new GoogleAuthorizationCodeTokenRequest(HTTP_TRANSPORT, JSON_FACTORY, appConfig.getGoogleClientId(), appConfig.getGoogleClientSecret(), code, currentUrl).execute(); }
Example #21
Source File: InstalledOAuth2Authenticator.java From adwords-alerting with Apache License 2.0 | 4 votes |
/** * Get New Credentials from the user from the command line OAuth2 dance. */ private Credential getNewOAuth2Credential() throws OAuthException { GoogleAuthorizationCodeFlow authorizationFlow = getAuthorizationFlow(); String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build(); System.out.println("\n**ACTION REQUIRED** Paste this url in your browser" + " and authenticate using your **AdWords Admin Email**: \n" + authorizeUrl); // Wait for the authorization code. System.out.println("\nType the code you received on the web page here: "); try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String authorizationCode = reader.readLine(); // Authorize the OAuth2 token. GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationFlow.newTokenRequest(authorizationCode); tokenRequest.setRedirectUri(CALLBACK_URL); GoogleTokenResponse tokenResponse = tokenRequest.execute(); // Create the credential. Credential credential = new GoogleCredential.Builder() .setClientSecrets(clientId, clientSecret) .setJsonFactory(new JacksonFactory()) .setTransport(new NetHttpTransport()) .build() .setFromTokenResponse(tokenResponse); // Get refresh token and prompt to save in properties file refreshToken = credential.getRefreshToken(); System.out.println("\n**ACTION REQUIRED** Put the following line in your properties file to" + " avoid OAuth authentication next time."); System.out.printf("refreshToken=%s\n\n", refreshToken); System.out.println("Then press enter to continue..."); reader.readLine(); return credential; } catch (IOException e) { throw new OAuthException("An error occured obtaining the OAuth2Credential", e.getCause()); } }
Example #22
Source File: AdWordsApiUtil.java From keyword-optimizer with Apache License 2.0 | 4 votes |
/** * Creates a new oauth2 credential based on the given client secrets. * * @param clientSecrets the client secrets (see developer console) * @return the newly created credential * @throws IOException in case of an error reading the configuration files */ private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets) throws IOException { GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow .Builder( new NetHttpTransport(), new JacksonFactory(), clientSecrets, Lists.newArrayList(SCOPE)) // 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 api.adwords.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, UTF_8)).readLine(); // Authorize the OAuth2 token. GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationFlow.newTokenRequest(authorizationCode); tokenRequest.setRedirectUri(CALLBACK_URL); GoogleTokenResponse tokenResponse = tokenRequest.execute(); // Create the OAuth2 credential. GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .setClientSecrets(clientSecrets) .build(); // Set authorized credentials. credential.setFromTokenResponse(tokenResponse); return credential; }