List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential setFromTokenResponse
@Override
public GoogleCredential setFromTokenResponse(TokenResponse tokenResponse)
From source file:adwords.axis.auth.GetRefreshToken.java
License:Open Source License
private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets) throws Exception { 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)).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; }
From source file:cn.edu.fudan.se.helpseeking.test.GetRefreshToken.java
License:Open Source License
private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets) throws Exception { 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.dfp.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. GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()).setClientSecrets(clientSecrets).build(); // Set authorized credentials. credential.setFromTokenResponse(tokenResponse); return credential; }
From source file:com.alow.servlet.ConnectServlet.java
License:Open Source License
/** * Exposed as `POST /api/connect`./*from w ww .j a va2 s . co m*/ * * Takes the following payload in the request body. The payload represents * all of the parameters that are required to authorize and connect the user * to the app. * { * "state":"", * "access_token":"", * "token_type":"", * "expires_in":"", * "code":"", * "id_token":"", * "authuser":"", * "session_state":"", * "prompt":"", * "client_id":"", * "scope":"", * "g_user_cookie_policy":"", * "cookie_policy":"", * "issued_at":"", * "expires_at":"", * "g-oauth-window":"" * } * * Returns the following JSON response representing the User that was * connected: * { * "id":0, * "googleUserId":"", * "googleDisplayName":"", * "googlePublicProfileUrl":"", * "googlePublicProfilePhotoUrl":"", * "googleExpiresAt":0 * } * * Issues the following errors along with corresponding HTTP response codes: * 401: The error from the Google token verification end point. * 500: "Failed to upgrade the authorization code." This can happen during * OAuth v2 code exchange flows. * 500: "Failed to read token data from Google." * This response also sends the error from the token verification * response concatenated to the error message. * 500: "Failed to query the Google+ API: " * This error also includes the error from the client library * concatenated to the error response. * 500: "IOException occurred." The IOException could happen when any * IO-related errors occur such as network connectivity loss or local * file-related errors. * * @see javax.servlet.http.HttpServlet#doPost( * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { TokenData accessToken = null; try { // read the token accessToken = Jsonifiable.fromJson(req.getReader(), TokenData.class); } catch (IOException e) { sendError(resp, 400, "Unable to read auth result from request body"); } // Create a credential object. GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY) .setTransport(TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build(); try { if (accessToken.code != null) { // exchange the code for a token (Web Frontend) GoogleTokenResponse tokenFromExchange = exchangeCode(accessToken); credential.setFromTokenResponse(tokenFromExchange); } else { if (accessToken.access_token == null) { sendError(resp, 400, "Missing access token in request."); } // use the token received from the client credential.setAccessToken(accessToken.access_token).setRefreshToken(accessToken.refresh_token) .setExpiresInSeconds(accessToken.expires_in) .setExpirationTimeMilliseconds(accessToken.expires_at); } // ensure that we consider logged in the user that owns the access token String tokenGoogleUserId = verifyToken(credential); User user = saveTokenForUser(tokenGoogleUserId, credential); // save the user in the session HttpSession session = req.getSession(); session.setAttribute(CURRENT_USER_SESSION_KEY, user.id); generateFriends(user, credential); sendResponse(req, resp, user); } catch (TokenVerificationException e) { sendError(resp, 401, e.getMessage()); } catch (TokenResponseException e) { sendError(resp, 500, "Failed to upgrade the authorization code."); } catch (TokenDataException e) { sendError(resp, 500, "Failed to read token data from Google. " + e.getMessage()); } catch (IOException e) { sendError(resp, 500, e.getMessage()); } catch (GoogleApiException e) { sendError(resp, 500, "Failed to query the Google+ API: " + e.getMessage()); } catch (DaoException e) { sendError(resp, 500, "Failed to access database: " + e.getMessage()); } catch (EntityExistsException e) { sendError(resp, 500, "Entity already exists: " + e.getMessage()); } }
From source file:com.google.plus.samples.photohunt.ConnectServlet.java
License:Open Source License
/** * Exposed as `POST /api/connect`.//www . j a v a 2s. c o m * <p> * Takes the following payload in the request body. Payload represents all * parameters required to authorize and/or connect. * { * "state":"", * "access_token":"", * "token_type":"", * "expires_in":"", * "code":"", * "id_token":"", * "authuser":"", * "session_state":"", * "prompt":"", * "client_id":"", * "scope":"", * "g_user_cookie_policy":"", * "cookie_policy":"", * "issued_at":"", * "expires_at":"", * "g-oauth-window":"" * } * <p> * Returns the following JSON response representing the User that was * connected: * { * "id":0, * "googleUserId":"", * "googleDisplayName":"", * "googlePublicProfileUrl":"", * "googlePublicProfilePhotoUrl":"", * "googleExpiresAt":0 * } * <p> * Issues the following errors along with corresponding HTTP response codes: * 401: error from token verification end-point. * 500: "Failed to upgrade the authorization code." (for code exchange flows) * 500: "Failed to read token data from Google." * + error from reading token verification response. * 500: "Failed to query the Google+ API: " + error from client library. * 500: IOException occurred (several ways this could happen). * * @see javax.servlet.http.HttpServlet#doPost( *javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { TokenData accessToken = null; try { // read the token accessToken = Jsonifiable.fromJson(req.getReader(), TokenData.class); } catch (IOException e) { sendError(resp, 400, "Unable to read auth result from request body"); } // Create a credential object. GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY) .setTransport(TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build(); try { if (accessToken.code != null) { // exchange the code for a token (Web Frontend) GoogleTokenResponse tokenFromExchange = exchangeCode(accessToken); credential.setFromTokenResponse(tokenFromExchange); } else { // use the token received from the client credential.setAccessToken(accessToken.access_token).setRefreshToken(accessToken.refresh_token) .setExpiresInSeconds(accessToken.expires_in) .setExpirationTimeMilliseconds(accessToken.expires_at); } // ensure that we consider logged in the user that owns the access token String tokenGoogleUserId = verifyToken(credential); User user = saveTokenForUser(tokenGoogleUserId, credential); // save the user in the session HttpSession session = req.getSession(); session.setAttribute(CURRENT_USER_SESSION_KEY, user.id); generateFriends(user, credential); sendResponse(req, resp, user); } catch (TokenVerificationException e) { sendError(resp, 401, e.getMessage()); } catch (TokenResponseException e) { sendError(resp, 500, "Failed to upgrade the authorization code."); } catch (TokenDataException e) { sendError(resp, 500, "Failed to read token data from Google. " + e.getMessage()); } catch (IOException e) { sendError(resp, 500, e.getMessage()); } catch (GoogleApiException e) { sendError(resp, 500, "Failed to query the Google+ API: " + e.getMessage()); } }
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 ww w . j av a 2s . c o 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:it.polimi.meteocal.ejb.HandleAuthGoogleImpl.java
License:Open Source License
/** * Method that return the Plus object that allows the access to the * GooglePlus API/*from w w w .j av a2 s . co m*/ * * @param user the user in MeteoCal * @return null if there was a problem with the creation of the Plus object */ public static Plus getPlusObject(User user) { Plus plus = null; final User utente2 = user; if (user.getGoogleToken() == null) { // Case in wich google plus is not connected return null; } try { HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()).setClientSecrets(CLIENT_ID, CLIENT_SECRET) .addRefreshListener(new CredentialRefreshListener() { @Override public void onTokenResponse(Credential credential, TokenResponse tokenResponse) { HandleAuthGoogleImpl.setGoogleToken(credential, tokenResponse, utente2); // Handle success. LOGGER.log(Level.INFO, "Credential was refreshed successfully."); } @Override public void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse) { // Handle error. LOGGER.log(Level.ERROR, "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( JSON_FACTORY.fromString(user.getGoogleToken(), GoogleTokenResponse.class)); /* Though not necessary when first created, you can manually refresh the token, which is needed after 60 minutes. */ if (credential.getExpiresInSeconds() < 1) { boolean ref = credential.refreshToken(); LOGGER.log(Level.INFO, "Refresh token: " + ref); LOGGER.log(Level.INFO, "Access token: " + credential.getAccessToken()); LOGGER.log(Level.INFO, "Refresh token: " + credential.getRefreshToken()); } // Create a new authorized API client. plus = new Plus.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME) .build(); } catch (IOException | GeneralSecurityException e) { LOGGER.log(Level.ERROR, e, e); } return plus; }
From source file:it.polimi.meteocal.ejb.HandleAuthGoogleImpl.java
License:Open Source License
@Override public boolean doLoginGoogle(String code) { try {/* w w w. jav a 2 s. c o m*/ httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleTokenResponse tokenResponse = flow.newTokenRequest(code) .setRedirectUri("http://www.meteocal.tk/MeteoCal-web/loginGoogle.xhtml").execute(); GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()).setClientSecrets(CLIENT_ID, CLIENT_SECRET) .addRefreshListener(new RefreshListener()).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(); String tokenGoogle = tokenResponse.toString(); // Insert new data in the DB Plus plus = new Plus.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); Person mePerson = plus.people().get("me").execute(); if (!AuthUtil.isUserLogged()) { // Saves the new data of the user in the DB User user = null; TypedQuery<User> q = em.createNamedQuery(User.FIND_BY_GOOGLE_ID, User.class); q.setParameter("googleId", mePerson.getId()); TypedQuery<User> q2 = em.createNamedQuery(User.FIND_BY_EMAIL, User.class); if (mePerson.getEmails() != null) { q2.setParameter("email", mePerson.getEmails().get(0).getValue()); } else { q2.setParameter("email", ""); } if (q.getResultList().isEmpty() && q2.getResultList().isEmpty()) { // The user is not in the system user = new User(); user.setGoogleId(mePerson.getId()); user.setGoogleToken(tokenGoogle); user.setFirstName(mePerson.getName().getGivenName()); user.setLastName(mePerson.getName().getFamilyName()); user.setAvatar(mePerson.getImage().getUrl()); if (mePerson.getEmails() != null) { user.setEmail(mePerson.getEmails().get(0).getValue()); } if (mePerson.getBirthday() != null) { try { user.setDateBirth(new SimpleDateFormat("MM/dd").parse(mePerson.getBirthday())); } catch (ParseException ex) { LOGGER.log(Level.WARN, ex); } } try { user.setPassword(PasswordHash.createHash(user.getFirstName() + "." + user.getLastName())); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { LOGGER.log(Level.FATAL, ex, ex); } LOGGER.log(Level.INFO, user.toString()); Setting setting = new Setting(); setting.setTimeZone(TimeZone.getTimeZone("GMT+1")); user.setSetting(setting); em.persist(user); em.flush(); em.refresh(user); } else if (!q.getResultList().isEmpty()) { // The user is already in the system LOGGER.log(Level.INFO, "User already registered with Google"); user = q.getResultList().get(0); if (tokenGoogle.contains("refresh_token")) { LOGGER.log(Level.INFO, "GoogleToken updated"); user.setGoogleToken(tokenGoogle); em.merge(user); em.flush(); } } else { LOGGER.log(Level.INFO, "User already registered with classic method"); user = q2.getResultList().get(0); //TODO merge informazioni da google mancanti em.merge(user); em.flush(); } // Make the session for the user AuthUtil.makeUserSession(user.getId()); } else { // User already registered in the system User utente = em.find(User.class, AuthUtil.getUserID()); TypedQuery<User> q = em.createNamedQuery(User.FIND_BY_GOOGLE_ID, User.class); q.setParameter("googleId", mePerson.getId()); if (q.getResultList().isEmpty()) { // The user account isn't already present in the db so set the new GooglePlus data utente.setGoogleId(mePerson.getId()); utente.setGoogleToken(tokenGoogle); em.merge(utente); em.flush(); } else { // User account already in the system LOGGER.log(Level.INFO, "User already registered with GooglePlus"); User oldUser = q.getResultList().get(0); if (!Objects.equals(utente.getId(), oldUser.getId())) { // Need to merge the two account utente = HandleUserImpl.mergeUserAccount(utente, oldUser); // set the new GooglePlus data utente.setGoogleId(mePerson.getId()); utente.setGoogleToken(tokenGoogle); em.merge(utente); em.flush(); // Transfer all the settings HandleUserImpl.mergeOldUserNewUser(em, utente, oldUser); em.remove(oldUser); em.flush(); } } } } catch (IOException e) { LOGGER.log(Level.ERROR, e); return false; } catch (GeneralSecurityException ex) { LOGGER.log(Level.ERROR, ex); } return true; }