GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, clientId, clientSecret, Arrays.asList(CalendarScopes.CALENDAR)).setAccessType("online") .setApprovalPrompt("auto").build(); String url = flow.newAuthorizationUrl().setRedirectUri(redirectUrl).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(); GoogleTokenResponse response = flow.newTokenRequest(code) .setRedirectUri(redirectUrl).execute(); GoogleCredential credential = new GoogleCredential() .setFromTokenResponse(response); // Create a new authorized API client Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential).build();
@Override public GoogleAuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) { // don't need to specify clientId & clientSecret because specifying clientAuthentication // don't want to specify redirectUri to give control of it to user of this class return new GoogleAuthorizationCodeTokenRequest(getTransport(), getJsonFactory(), getTokenServerEncodedUrl(), "", "", authorizationCode, "").setClientAuthentication( getClientAuthentication()) .setRequestInitializer(getRequestInitializer()).setScopes(getScopes()); }
@Override public GoogleAuthorizationCodeFlow build() { return new GoogleAuthorizationCodeFlow(this); }
GoogleAuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow .Builder(httpTransport, jsonFactory, clientId, clientSecret, scopes) .setCredentialDataStore(new MemoryDataStoreFactory().getDataStore("tokens")) .build(); String userId = "user-id"; Credential credential = authorizationCodeFlow.loadCredential(userId); if (credential == null) { GoogleAuthorizationCodeRequestUrl authorizationUrl = authorizationCodeFlow.newAuthorizationUrl(); authorizationUrl.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI); LOGGER.error("Please, authorize application. Visit {}", authorizationUrl); Scanner s = new Scanner(System.in); String code = s.nextLine(); GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(code); tokenRequest.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI); GoogleTokenResponse tokenResponse = tokenRequest.execute(); credential = authorizationCodeFlow.createAndStoreCredential(tokenResponse, userId); }
System.out.println("Flujo string --> " +flujo.toString()); System.out.println("Flujo token encodeurl --> " +flujo.getTokenServerEncodedUrl()); System.out.println("Flujo access_type --> " +flujo.getAccessType()); //ahora mismo es null System.out.println("Flujo client_id --> " +flujo.getClientId()); System.out.println("Flujo scopes as string --> " +flujo.getScopesAsString()); System.out.println("Flujo nuevo token --> " +flujo.newTokenRequest(code));
HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleAuthorizationCodeFlow 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(); res.sendRedirect(url);
TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUrl).execute(); Credential credential = flow.createAndStoreCredential(response, "userID"); com.google.api.services.calendar.Calendar client = new com.google.api.services.calendar.Calendar.Builder(httpTransport, JSON_FACTORY, credential)
// FileDataStoreFactory is used to create new credentials and // simultaneously loads previously generated credentials from a file // Specify a location where the file should be stored via DIRECTORY // The file is automatically generated and encrypted FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(DIRECTORY)); // Create the GoogleAuthorizationCodeFlow. This is needed to get the user (you?) // approval (you need that so you can access data). getClientSecrets() returns a // GoogleClientSecrets. If you want to, I can provide some code :) // Here you also specify your scopes GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, getClientSecrets(), Arrays.asList(scope)) .setCredentialDataStore(StoredCredential.getDefaultDataStore(fileDataStoreFactory)).build(); // With the GoogleAuthorizationCodeFlow you can create a Credential Credential cred = flow.loadCredential("user"); // Check if the cred is null or expired (credentials last about an hour I think) if(cred == null || (cred.getExpiresInSeconds() < 100 && !cred.refreshToken())){ // If it is expired, you need to refresh it via UserAuthorization, again, if you // want to I can provide an example code GoogleTokenResponse resp = getUserAuthorization(flow); if(resp == null){ return null; } cred = flow.createAndStoreCredential(resp, "user"); }
public void importCalendarList(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession session = request.getSession(); String staffKey = (String) session.getAttribute("staffKey"); ContactJdo staffDetails = staff.getStaffDetail(staffKey); String code = request.getParameter("code"); String calendarId=""; GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, client_id, client_secret, scopes).build(); GoogleTokenResponse res = flow.newTokenRequest(code).setRedirectUri(redirect_uri).execute(); String refreshToken = res.getRefreshToken(); String accessToken = res.getAccessToken(); List <CalendarListEntry>list1= getCalendars(accessToken); for(CalendarListEntry temp:list1) { System.out.println(temp.getId()); }}
@Override public GoogleAuthorizationCodeRequestUrl newAuthorizationUrl() { // don't want to specify redirectUri to give control of it to user of this class return new GoogleAuthorizationCodeRequestUrl( getAuthorizationServerEncodedUrl(), getClientId(), "", getScopes()).setAccessType( accessType).setApprovalPrompt(approvalPrompt); }
HttpTransport transport = new NetHttpTransport(); List<String> applicationScopes = Arrays.asList( PlusScopes.USERINFO_EMAIL, PlusScopes.USERINFO_PROFILE ); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( transport, JacksonFactory.getDefaultInstance(), "your-client-id.apps.googleusercontent.com", "your-client-secret", applicationScopes).build(); String userId = googleTokenResponse.parseIdToken().getPayload().getSubject(); Credential credential = flow.createAndStoreCredential(googleTokenResponse, userId); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v1/userinfo"); HttpRequest request = requestFactory.buildGetRequest(url); String userIdentity = request.execute().parseAsString();
// Fetch credential using the GoogleAuthorizationCodeFlow GoogleAuthorizationCodeFlow authorizationCodeFlow; Credential credential = authorizationCodeFlow.loadCredential(userId); if (credential != null) { try { // refresh the credential to see if the refresh token is still valid credential.refreshToken(); System.out.println("Refreshed: expires in: " + credential.getExpiresInSeconds()); } catch (TokenResponseException e) { // process exception here. // This will catch the Exception. // This Exception contains the HTTP status and reason etc. // In case of a revoke, this will throw something like a 401 - "invalid_grant" return; } } else { // No credential yet known. // Flow for creating a new credential here }
Credential credential = flow.loadCredential(user.getEmailAddress()); String url = flow.newAuthorizationUrl() .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI) .build(); GoogleTokenResponse response = flow.newTokenRequest(code) .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI) .execute(); flow.createAndStoreCredential(response, user.getEmailAddress());
public void authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String client_id = "xxxx"; String redirect_uri = "xxxxxx"; String scope = "https://www.googleapis.com/auth/calendar"; String client_secret = "xxxxxx"; List <String> scopes; HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); scopes = new LinkedList<String>(); scopes.add(scope); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, client_id, client_secret, scopes).build(); GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl(); url.setRedirectUri(redirect_uri); url.setApprovalPrompt("force"); url.setAccessType("offline"); String authorize_url = url.build(); response.sendRedirect(authorize_url); }
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE)) .setAccessType("offline") .setApprovalPrompt("auto").build(); GoogleTokenResponse response = null; try { response = flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute(); } catch (IOException e) { e.printStackTrace(); } GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
.setApprovalPrompt("auto").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:"); String code = br.readLine(); GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute(); GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
final GoogleAuthorizationCodeFlow.Builder builder = new GoogleAuthorizationCodeFlow.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), "client-ID", "client-secret", "scopes..."); final GoogleAuthorizationCodeFlow flow = builder.build(); final GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl(); url.setState("base-64-encoded-state..."); url.put("login_hint", "bozo@clown.com"); return builder .setAuthorizationServerEncodedUrl(url.build()) .setAccessType("offline") .setApprovalPrompt("force") .build();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jacksonFactory, CLIENT_ID, CLIENT_SECRET, scopes).setAccessType("online").setApprovalPrompt("auto").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(); GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute(); System.out.println("Response : " + response.toPrettyString()); GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
private String authorize(String redirectUri) { AuthorizationCodeRequestUrl authorizationUrl; Details web = new Details(); GoogleCalendarSettings googleCalendarSettings = settingsService.getSettings().getCalendarSettings().getGoogleCalendarSettings(); web.setClientId(googleCalendarSettings.getClientId()); web.setClientSecret(googleCalendarSettings.getClientSecret()); GoogleClientSecrets clientSecrets = new GoogleClientSecrets(); clientSecrets.setWeb(web); flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, Collections.singleton(CalendarScopes.CALENDAR)) .setApprovalPrompt("force") .setAccessType("offline") .build(); authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUri); LOG.info("using authorizationUrl " + authorizationUrl); return authorizationUrl.build(); } }
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); } }