List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential.Builder GoogleCredential.Builder
GoogleCredential.Builder
From source file:gplus.java
private void callGoogle(HttpServletRequest request, HttpServletResponse response) throws IOException { ByteArrayOutputStream resultStream = new ByteArrayOutputStream(); try {//from www .j a v a 2 s . c o m getContent(request.getInputStream(), resultStream); } catch (IOException ex) { Logger.getLogger(gplus.class.getName()).log(Level.SEVERE, null, ex); } try { code = new String(resultStream.toByteArray(), "UTF-8"); System.out.println(code); } catch (UnsupportedEncodingException ex) { Logger.getLogger(gplus.class.getName()).log(Level.SEVERE, null, ex); } //Create a token try { tokenResponse = new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, code, "postmessage").execute(); GoogleIdToken idToken = tokenResponse.parseIdToken(); String gplusId = idToken.getPayload().getSubject(); tokenData = tokenResponse.toString(); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(GSON.toJson("Successfully connected user.")); } catch (TokenResponseException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().print(GSON.toJson("Failed to upgrade the authorization code.")); } catch (IOException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().print(GSON.toJson("Failed to read token data from Google. " + e.getMessage())); } try { // Build credential from stored token data. GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY) .setTransport(TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build() .setFromTokenResponse(JSON_FACTORY.fromString(tokenData, GoogleTokenResponse.class)); // Create a new authorized API client. Plus service = new Plus.Builder(TRANSPORT, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); // Get a list of people that this user has shared with this app. PeopleFeed people = service.people().list("me", "visible").execute(); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(GSON.toJson(people)); System.out.println(people.toString()); } catch (IOException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().print(GSON.toJson("Failed to read data from Google. " + e.getMessage())); } }
From source file:com.example.listmaker.server.auth.GPlus.java
License:Open Source License
private User getUserInfo(GoogleTokenResponse accessToken) { try {//ww w .j av a 2s .com // Build credential from stored token data. GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY) .setTransport(TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build() .setFromTokenResponse( JSON_FACTORY.fromString(accessToken.toString(), GoogleTokenResponse.class)); // Create a new authorized API client. Plus service = new Plus.Builder(TRANSPORT, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); // Get a list of people that this user has shared with this app. Person me = service.people().get("me").execute(); User newUser = new User(); GoogleIdToken idToken = accessToken.parseIdToken(); newUser.setEmailAddress(idToken.getPayload().getEmail()); newUser.setGoogleId(idToken.getPayload().getSubject()); newUser.setFirstName(me.getName().getGivenName()); newUser.setLastName(me.getName().getFamilyName()); String imageUrl = me.getImage().getUrl(); newUser.setImgUrl(imageUrl); return newUser; // PeopleFeed people = service.people().list("me", "visible").execute(); } catch (IOException e) { throw new RestException(e); } }
From source file:com.example.listmaker.server.auth.GPlus.java
License:Open Source License
/** * Get list of people user has shared with this app. *//*ww w .jav a2 s.c o m*/ private Person listPeople() { String tokenData = AuthFilter.getToken(); try { // Build credential from stored token data. GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY) .setTransport(TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build() .setFromTokenResponse(JSON_FACTORY.fromString(tokenData, GoogleTokenResponse.class)); // Create a new authorized API client. Plus service = new Plus.Builder(TRANSPORT, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); // Get a list of people that this user has shared with this app. Person me = service.people().get("me").execute(); // PeopleFeed people = service.people().list("me", "visible").execute(); return me; } catch (IOException e) { throw new RestException(e); } }
From source file:com.google.sites.liberation.util.Auth.java
License:Apache License
/** * Get new credentials for access Token given by user *//* www . j a v a 2s .co m*/ public Credential getCredentials(String accessToken) throws IOException { HttpTransport transport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, accessToken, REDIRECT_URI).execute(); LOGGER.debug("New authorization data has been downloaded - accessToken: " + response.getAccessToken() + ", refreshToken: " + response.getRefreshToken()); return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET).setJsonFactory(jsonFactory) .setTransport(transport).build().setAccessToken(response.getAccessToken()) .setRefreshToken(response.getRefreshToken()); }
From source file:com.google.sites.liberation.util.Auth.java
License:Apache License
/** * Method refreshes access token by given REFRESH_TOKEN *///from w w w. j av a 2 s . co m public Credential refreshAccessToken() throws IOException { HttpTransport transport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); TokenResponse response = new TokenResponse(); try { response = new GoogleRefreshTokenRequest(transport, jsonFactory, REFRESH_TOKEN, CLIENT_ID, CLIENT_SECRET).execute(); LOGGER.debug("New accessToken (" + response.getAccessToken() + ") has been downloaded (by refreshToken in token file) with Google API Authorization!"); } catch (TokenResponseException e) { LOGGER.warn("Downloaded accessToken is empty! Please check provided token (propriety of -t parameter)"); if (e.getDetails() != null) { System.err.println("Error: " + e.getDetails().getError()); if (e.getDetails().getErrorDescription() != null) { System.err.println(e.getDetails().getErrorDescription()); } if (e.getDetails().getErrorUri() != null) { System.err.println(e.getDetails().getErrorUri()); } } else { System.err.println(e.getMessage()); } } return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET).setJsonFactory(jsonFactory) .setTransport(transport).build().setAccessToken(response.getAccessToken()); }
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;//from w w w . java 2 s .c o m 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; }