List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeTokenRequest GoogleAuthorizationCodeTokenRequest
public GoogleAuthorizationCodeTokenRequest(HttpTransport transport, JsonFactory jsonFactory, String clientId,
String clientSecret, String code, String redirectUri)
From source file:gplus.java
private void callGoogle(HttpServletRequest request, HttpServletResponse response) throws IOException { ByteArrayOutputStream resultStream = new ByteArrayOutputStream(); try {/* w ww .j a va 2 s.co 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:ch.chnoch.appengine.bunddownloader.CredentialMediator.java
License:Apache License
/** * Exchange an authorization code for a credential. * * @param authorizationCode Authorization code to exchange for OAuth 2.0 * credentials.//www .jav a 2 s.co m * @return Credential representing the upgraded authorizationCode. * @throws CodeExchangeException An error occurred. */ private Credential exchangeCode(String authorizationCode) throws CodeExchangeException { // Talk to Google and upgrade the given authorization code to an access // token and hopefully a refresh token. try { GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY, secrets.getWeb().getClientId(), secrets.getWeb().getClientSecret(), authorizationCode, secrets.getWeb().getRedirectUris().get(0)).execute(); return buildEmptyCredential().setFromTokenResponse(response); } catch (IOException e) { e.printStackTrace(); throw new CodeExchangeException(); } }
From source file:com.alow.servlet.ConnectServlet.java
License:Open Source License
/** * Exchanges the `code` member of the given AccessToken object, and returns * the relevant GoogleTokenResponse.//w w w. j a v a 2s. c o m * @param accessToken Container of authorization code to exchange. * @return Token response from Google indicating token information. * @throws TokenDataException Failed to exchange code (code invalid). */ private GoogleTokenResponse exchangeCode(TokenData accessToken) throws TokenDataException { try { // Upgrade the authorization code into an access and refresh token. GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, accessToken.code, "postmessage").execute(); return tokenResponse; } catch (IOException e) { throw new TokenDataException(e.getMessage()); } }
From source file:com.dhara.googlecalendartrial.MainActivity.java
private void setUp(final String userAccount) { try {/*from w w w. j a va 2 s .c o m*/ String clientId = "424045474279-tdm2pud0f32vovicoajj3hul5ot349r7.apps.googleusercontent.com"; String clientSecret = "pjCbZO9lwGudNtk9CMKQ7GGx"; // Or your redirect URL for web based applications. String redirectUrl = "https://localhost/oauth2callback"; //"urn:ietf:wg:oauth:2.0:oob"; String scope = "https://www.googleapis.com/auth/calendar"; java.util.List<String> listOfScope = new ArrayList<String>(); listOfScope.add(scope); Collection<String> scopes = listOfScope; HttpTransport httpTransport = AndroidHttp.newCompatibleTransport(); // Step 1: Authorize --> String authorizationUrl = new GoogleAuthorizationCodeRequestUrl(clientId, redirectUrl, scopes).build(); // Point or redirect your user to the authorizationUrl. System.out.println("Go to the following link in your browser:"); System.out.println(authorizationUrl); // Read the authorization code from the standard input stream. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What is the authorization code?"); String code = in.readLine(); // End of Step 1 <-- // Step 2: Exchange --> final GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(httpTransport, jsonFactory, clientId, clientSecret, code, redirectUrl).execute(); // End of Step 2 <-- /*GoogleAccessProtectedResource accessProtectedResource = new Google( response.getAccessToken(), httpTransport, jsonFactory, clientId, clientSecret, response.getRefreshToken());*/ credential = new GoogleCredential().setAccessToken(response.getAccessToken()); Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential) .setApplicationName("GoogleCalendarTrial").setHttpRequestInitializer(credential) .setCalendarRequestInitializer(new CalendarRequestInitializer() { @Override protected void initializeCalendarRequest(CalendarRequest<?> calendarRequest) throws IOException { super.initializeCalendarRequest(calendarRequest); ArrayMap<String, Object> customKeys = new ArrayMap<String, Object>(); customKeys.put("xoauth_requestor_id", userAccount); calendarRequest.setUnknownKeys(customKeys); calendarRequest.setOauthToken(response.getAccessToken()); calendarRequest.setKey(apiKey); } }).build(); List find = service.events().list("primary"); Events events = find.execute(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.example.contactmgr.server.auth.GPlus.java
License:Open Source License
/** * Upgrade given auth code to token, and store it in the session. * POST body of request should be the authorization code. * Example URI: /login?code=/*from w ww . jav a 2s.c o m*/ */ @GET @Path("login") public Response login(@QueryParam("code") String code, @Context HttpServletRequest req, @Context HttpServletResponse res) throws IOException { // already logged in if (AuthFilter.getUser() != null) { try { return Response.temporaryRedirect(new URI(getAppUrl(req))).build(); } catch (URISyntaxException e) { throw new RestException(e); } } try { // Upgrade the authorization code into an access and refresh token. String callbackUri = getCallbackURI(req); GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, code, callbackUri).execute(); // You can read the Google user ID in the ID token. // This sample does not use the user ID. GoogleIdToken idToken = tokenResponse.parseIdToken(); String email = idToken.getPayload().getEmail(); User user = appUserSvc.getRegisteredUser(email); if ((user == null) || user.getGoogleId() == null) { // Register new user User newUser = getUserInfo(tokenResponse); try { user = registerUser(newUser); } catch (DuplicateUserException e) { res.sendRedirect("/s/ar.html"); } } AuthFilter.login(user, tokenResponse.toString()); return Response.temporaryRedirect(new URI(getAppUrl(req))).build(); } catch (TokenResponseException e) { throw new RestException(e); } catch (IOException e) { throw new RestException(e); } catch (URISyntaxException e) { throw new RestException(e); } }
From source file:com.google.appengine.tck.teamcity.ReportsFeature.java
License:Open Source License
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 {/* w w w .j a v a 2 s . co m*/ 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); } }
From source file:com.google.plus.samples.haikuplus.Authenticate.java
License:Open Source License
/** * Creates a token verifier object using the client secret values provided by client_secrets.json. * * @param authorization the authorization code to be exchanged for a bearer token once verified * @param redirectUri the redirect URI to be used for token exchange, from the APIs console. *//*from w w w. j ava 2 s.co m*/ @VisibleForTesting GoogleAuthorizationCodeTokenRequest createTokenExchanger(String authorization, String redirectUri) { return new GoogleAuthorizationCodeTokenRequest(HaikuPlus.TRANSPORT, HaikuPlus.JSON_FACTORY, getClientId(), getClientSecret(), authorization, redirectUri); }
From source file:com.google.plus.samples.photohunt.ConnectServlet.java
License:Open Source License
/** * Exchanges the `code` member of the given AccessToken object, and returns * the relevant GoogleTokenResponse./*w w w. j a va 2s. co m*/ * * @param accessToken Container of authorization code to exchange. * @return Token response from Google indicating token information. * @throws TokenDataException Failed to exchange code (code invalid). */ private GoogleTokenResponse exchangeCode(TokenData accessToken) throws TokenDataException { try { // Upgrade the authorization code into an access and refresh token. return new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, accessToken.code, "postmessage").execute(); } catch (IOException e) { throw new TokenDataException(e.getMessage()); } }
From source file:com.google.refine.extension.gdata.GDataExtension.java
License:Open Source License
static public String getTokenFromCode(ButterflyModule module, HttpServletRequest request) throws MalformedURLException { String redirectUrl = makeRedirectUrl(module, request); StringBuffer fullUrlBuf = request.getRequestURL(); if (request.getQueryString() != null) { fullUrlBuf.append('?').append(request.getQueryString()); }//from ww w . j a v a2 s. com AuthorizationCodeResponseUrl authResponse = new AuthorizationCodeResponseUrl(fullUrlBuf.toString()); // check for user-denied error if (authResponse.getError() != null) { // authorization denied... } else { // request access token using authResponse.getCode()... String code = authResponse.getCode(); try { GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, code, redirectUrl).execute(); String token = response.getAccessToken(); return token; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; }
From source file:com.google.sites.liberation.util.Auth.java
License:Apache License
/** * Get new credentials for access Token given by user *//* w w w .ja v a 2 s. c o 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()); }