List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newTokenRequest
@Override
public GoogleAuthorizationCodeTokenRequest newTokenRequest(String authorizationCode)
From source file:org.exoplatform.clouddrive.gdrive.CredentialUtils.java
License:Open Source License
/** * Exchange an authorization code for OAuth 2.0 credentials. * /*from w w w .jav a2s .com*/ * @return OAuth 2.0 credentials. * @throws CodeExchangeException An error occurred. */ public Credential getCredential(String code) throws IOException { GoogleAuthorizationCodeFlow flow = getFlow(); GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute(); return flow.createAndStoreCredential(response, null); }
From source file:org.exoplatform.clouddrive.gdrive.GoogleDriveAPI.java
License:Open Source License
/** * Create Google Drive API from OAuth2 authentication code. * //from w ww .j a v a2s.co m * @param clientId {@link String} * @param clientSecret {@link String} * @param authCode {@link String} * @throws GoogleDriveException if authentication failed for any reason. * @throws CloudDriveException if credentials store exception happen */ GoogleDriveAPI(String clientId, String clientSecret, String authCode, String redirectUri) throws GoogleDriveException, CloudDriveException { // use clean token, it will be populated with actual credentials as CredentialRefreshListener this.token = new AuthToken(); GoogleAuthorizationCodeFlow authFlow; try { authFlow = createFlow(clientId, clientSecret, token); } catch (IOException e) { throw new GoogleDriveException("Error creating authentication flow: " + e.getMessage(), e); } GoogleTokenResponse response; try { // Exchange an authorization code for OAuth 2.0 credentials. response = authFlow.newTokenRequest(authCode).setRedirectUri(redirectUri).execute(); } catch (IOException e) { throw new GoogleDriveException("Error authenticating user code: " + e.getMessage(), e); } try { this.credential = authFlow.createAndStoreCredential(response, USER_ID); } catch (IOException e) { throw new CloudDriveException("Error storing user credential: " + e.getMessage(), e); } // XXX .setHttpRequestInitializer(new RequestInitializer() this causes OAuth2 401 Unauthorized this.drive = new Drive.Builder(new NetHttpTransport(), new JacksonFactory(), this.credential) .setApplicationName(APP_NAME).build(); this.oauth2 = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), this.credential) .setApplicationName(APP_NAME).build(); }
From source file:org.myLazyClock.restApi.MyLazyClockUserApi.java
License:Open Source License
@ApiMethod(name = "myLazyClockUser.link", httpMethod = ApiMethod.HttpMethod.POST, path = "myLazyClockUser") public MyLazyClockUserValid linkUser(@Named("code") String code, User user) throws UnauthorizedException, InternalServerErrorException { if (user == null) { throw new UnauthorizedException("Login Required"); }//from ww w. jav a2 s . com HttpTransport httpTransport = null; try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); } catch (GeneralSecurityException | IOException e) { throw new InternalServerErrorException(e); } JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, ConstantAPI.API_ID, ConstantAPI.API_SECRET, Arrays.asList(Constants.SCOPE_CALENDAR_READ)).build(); GoogleTokenResponse response = null; try { response = flow.newTokenRequest(code).setRedirectUri("postmessage").execute(); } catch (IOException e) { throw new InternalServerErrorException(e); } MyLazyClockUserValid isValid = MyLazyClockUserService.getInstance().add(user, response.getRefreshToken()); MyLazyClockMemcacheService.getInstance().cleanUserValidity(user); return isValid; }
From source file:org.vx68k.hudson.plugin.google.login.GoogleLoginService.java
License:Open Source License
/** * Handles an authorized redirection request. * * @param request HTTP servlet request/*w ww. j ava2 s.c o m*/ * @param code authorization code * @param state state in the authorization request * @return HTTP response for the request */ public HttpResponse doAuthorized(HttpServletRequest request, @QueryParameter(required = true) String code, @QueryParameter String state) { HttpSession session = request.getSession(); if (state != null) { if (!state.equals(session.getId())) { return HttpResponses.forbidden(); } } String from = (String) session.getAttribute(LOGIN_FROM_NAME); session.removeAttribute(LOGIN_FROM_NAME); if (from == null) { from = request.getContextPath() + "/"; } Hudson application = Hudson.getInstance(); GoogleLoginServiceProperty.Descriptor descriptor = application .getDescriptorByType(GoogleLoginServiceProperty.Descriptor.class); GoogleAuthorizationCodeFlow flow = descriptor.getAuthorizationCodeFlow(); GoogleAuthorizationCodeTokenRequest tokenRequest = flow.newTokenRequest(code); tokenRequest.setRedirectUri(getRedirectUri()); Userinfoplus userinfoplus; try { GoogleTokenResponse tokenResponse = tokenRequest.execute(); String accessToken = tokenResponse.getAccessToken(); Oauth2 oauth2 = new Oauth2(flow.getTransport(), flow.getJsonFactory(), flow.getRequestInitializer()); Oauth2.Userinfo userinfo = oauth2.userinfo(); Oauth2.Userinfo.Get userinfoGet = userinfo.get(); userinfoGet.setOauthToken(accessToken); userinfoplus = userinfoGet.execute(); } catch (IOException e) { return HttpResponses.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } if (!userinfoplus.isVerifiedEmail()) { return HttpResponses.forbidden(); } Identity identity = new Identity(userinfoplus); if (User.current() != null) { try { identity.addToCurrentUser(); } catch (IOException e) { return HttpResponses.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } } else { identity.signin(); } return HttpResponses.redirectTo(from); }
From source file:pkg398gmail.GmailApiQuickstart.java
public static void main(String[] args) throws IOException { HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH)); // Allow user to authorize via url. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE)).setAccessType("offline").setApprovalPrompt("force").build(); String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build(); System.out.println(//from w w w . jav a2 s. c o m "Please open the following URL in your browser then type" + " the authorization code:\n" + url); // Read code entered by user. 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(); System.out.println("refresh " + response.getRefreshToken()); /* online use GoogleCredential credential = new GoogleCredential() .setFromTokenResponse(response); */ // offline use. //http://stackoverflow.com/questions/15064636/googlecredential-wont-build-without-googlecredential-builder GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(jsonFactory).setClientSecrets(clientSecrets).build().setFromTokenResponse(response); // Create a new authorized Gmail API client Gmail service = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName(APP_NAME) .build(); // Retrieve a page of Threads; max of 100 by default. ListThreadsResponse threadsResponse = service.users().threads().list(USER).execute(); List<com.google.api.services.gmail.model.Thread> threads = threadsResponse.getThreads(); // Print ID of each Thread. for (com.google.api.services.gmail.model.Thread thread : threads) { System.out.println("Thread ID: " + thread.getId()); } // send message try { sendMessage(service, "me", createEmail("wra216@lehigh.edu", "me", "test", "test")); } catch (MessagingException ex) { Logger.getLogger(GmailApiQuickstart.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:souffle.Souffle.java
public static void main(String[] args) throws IOException { Souffle souffle = new Souffle(); HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE)).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();//from w w w . ja va 2s . co m GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute(); GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response); //Create a new authorized API client Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build(); //Insert a file File body = new File(); body.setTitle("My document"); body.setDescription("A test document"); body.setMimeType("text/plain"); java.io.File fileContent; try { fileContent = new java.io.File(souffle.getClass().getResource("document.txt").toURI()); FileContent mediaContent = new FileContent("text/plain", fileContent); File file = service.files().insert(body, mediaContent).execute(); System.out.println("File ID: " + file.getId()); } catch (URISyntaxException ex) { Logger.getLogger(Souffle.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:to.lean.tools.gmail.importer.gmail.Authorizer.java
License:Open Source License
public Credential get() { try {//from www. j av a2 s . c o m 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); } }
From source file:xsm.axis.auth.AdvancedCreateCredentialFromScratch.java
License:Open Source License
private static void authorize(CredentialStore credentialStore, 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://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow // for more information. GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder( new NetHttpTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET, Lists.newArrayList(SCOPE)) .setCredentialStore(credentialStore) // 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(); // Store the credential for the user. authorizationFlow.createAndStoreCredential(tokenResponse, userId); }