List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newTokenRequest
@Override
public GoogleAuthorizationCodeTokenRequest newTokenRequest(String authorizationCode)
From source file:adwords.axis.auth.AdvancedCreateCredentialFromScratch.java
License:Open Source License
private static void authorize(DataStoreFactory storeFactory, 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)) .setDataStoreFactory(storeFactory) // 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(); // Store the credential for the user. authorizationFlow.createAndStoreCredential(tokenResponse, userId); }
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:by.dev.madhead.gbp.tasks.gdrive.ObtainGoogleDriveTokensTask.java
License:Apache License
/** * Initiates Google Drive tokens obtaining flow. *//* w ww . ja va 2 s . com*/ @TaskAction public void run() { final Console console = System.console(); if (null == console) { throw new TaskExecutionException(this, new UnsupportedOperationException("This task cannot be run without console.")); } try { Preconditions.checkNotNull(this.clientId, "Google Drive client ID must not be null"); Preconditions.checkNotNull(this.clientSecret, "Google Drive client secret must not be null"); final HttpTransport transport = new NetHttpTransport(); final JsonFactory jsonFactory = new JacksonFactory(); final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, clientId, clientSecret, Arrays.asList(DriveScopes.DRIVE)).build(); final String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build(); System.out.println((new Ansi()).a("Navigate to the following url: ").fg(Ansi.Color.YELLOW).a(url) .reset().a(", and then paste the authorization code here:")); final String authorizationCode = console.readLine().trim(); final GoogleTokenResponse tokenResponse = flow.newTokenRequest(authorizationCode) .setRedirectUri(REDIRECT_URI).execute(); System.out.println( (new Ansi()).a("Your access token is ").fg(Ansi.Color.YELLOW).a(tokenResponse.getAccessToken()) .reset().a(". Store it somewhere for future use. It will expire in ") .a(tokenResponse.getExpiresInSeconds()).a(" seconds")); System.out.println((new Ansi()).a("Your refresh token is ").fg(Ansi.Color.YELLOW) .a(tokenResponse.getRefreshToken()).reset().a(". Store it somewhere for future use.")); } catch (IOException ioException) { throw new TaskExecutionException(this, ioException); } }
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.abubusoft.liferay.google.GoogleOAuth.java
License:Open Source License
protected Credential exchangeCode(long companyId, String authorizationCode, String redirectUri) throws CodeExchangeException { try {//from w w w .jav a 2 s . c om GoogleAuthorizationCodeFlow flow = getFlow(companyId); GoogleAuthorizationCodeTokenRequest token = flow.newTokenRequest(authorizationCode); token.setRedirectUri(redirectUri); GoogleTokenResponse response = token.execute(); return flow.createAndStoreCredential(response, null); } catch (Exception e) { System.err.println("An error occurred: " + e); throw new CodeExchangeException(); } }
From source file:com.compguide.web.google.calendar.api.GoogleCalendar.java
/** * Request for an access token using an authorization code. * * @throws IOException/*from w w w . java 2s. c o m*/ */ static Credential requestAccessToken(String code, User user) throws IOException { Credential credential = null; // Build flow and trigger user authorization request. GoogleAuthorizationCodeFlow flow = authorizationCodeFlow("online"); AuthorizationCodeTokenRequest tokenRequest = flow.newTokenRequest(code); tokenRequest.setRedirectUri(RedirectURI); try { // TokenResponse response // = flow.newTokenRequest(code).execute(); TokenResponse tokenResponse = tokenRequest.execute(); System.out.println("Access token: " + tokenResponse.getAccessToken()); //Now, with the token and user id, we have credentials credential = flow.createAndStoreCredential(tokenResponse, user.getIduser().toString()); } catch (TokenResponseException e) { if (e.getDetails() != null) { Logger.getLogger(GoogleCalendarController.class.getName()).log(Level.SEVERE, e.getDetails().getError(), e); if (e.getDetails().getErrorDescription() != null) { Logger.getLogger(GoogleCalendarController.class.getName()).log(Level.SEVERE, e.getDetails().getErrorDescription(), e); } if (e.getDetails().getErrorUri() != null) { Logger.getLogger(GoogleCalendarController.class.getName()).log(Level.SEVERE, e.getDetails().getErrorUri(), e); } } else { Logger.getLogger(GoogleCalendarController.class.getName()).log(Level.SEVERE, e.getMessage(), e); } } return credential; }
From source file:com.dnalog.fmrp.google.GoogleClientCredentials.java
License:Apache License
public static Credential authorize(GoogleClientSecrets clientSecrets, List scopes) throws Exception { String authorizationCode = ""; String authorizeUrl = new GoogleAuthorizationCodeRequestUrl(clientSecrets, (clientSecrets.getDetails().getRedirectUris().get(0)), scopes).setState("").build(); System.out.println("Paste this URL into a web browser to authorize BigQuery Access:\n" + authorizeUrl); System.out.println("... and type the code you received here: "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); authorizationCode = in.readLine();//w w w. j ava 2 s . c om GoogleAuthorizationCodeFlow flow = getFlow(clientSecrets, scopes); GoogleTokenResponse response = flow.newTokenRequest(authorizationCode) .setRedirectUri(clientSecrets.getDetails().getRedirectUris().get(0)).execute(); System.out.println("Token response: " + response); return flow.createAndStoreCredential(response, null); }
From source file:com.example.plusPreviewAppengineSample.PlusSampleAuthCallbackServlet.java
License:Apache License
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Note that this implementation does not handle the user denying authorization. GoogleAuthorizationCodeFlow authFlow = Utils.initializeFlow(); //if null then authorization was denied if (req.getParameter("code") == null) { resp.sendRedirect("/index.html"); return;//from w ww. j a va 2 s.com } // Exchange authorization code for user credentials. GoogleTokenResponse tokenResponse = authFlow.newTokenRequest(req.getParameter("code")) .setRedirectUri(Utils.getRedirectUri(req)).execute(); // Save the credentials for this user so we can access them from the main servlet. authFlow.createAndStoreCredential(tokenResponse, Utils.getUserId(req)); resp.sendRedirect(Utils.MAIN_SERVLET_PATH); }
From source file:com.fredericvauchelles.ConnectMojo.java
License:Apache License
@Override public void execute() throws MojoExecutionException { try {/*w w w. j a v a 2s .c om*/ Properties clientProperties = new Properties(); clientProperties.load(new FileInputStream(googleClientProperties)); String clientId = clientProperties.getProperty("clientId"); String clientSecret = clientProperties.getProperty("clientSecret"); authToken = authToken == null ? clientProperties.getProperty("authToken") : authToken; HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); if (clientId == null) throw new Exception("clientId is not defined in " + googleClientProperties.getAbsolutePath()); if (clientSecret == null) throw new Exception("clientSecret is not defined in " + googleClientProperties.getAbsolutePath()); MavenCredentialStore store = new MavenCredentialStore(googleDrivePropertiesDirectory, getLog()); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientId, clientSecret, Arrays.asList(DriveScopes.DRIVE)).setAccessType("offline") .setApprovalPrompt("auto").setCredentialStore(store).build(); Credential credential = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(jsonFactory).setClientSecrets(clientId, clientSecret).build(); if (!store.load("service", credential)) { if (authToken != null) { try { GoogleTokenResponse response = flow.newTokenRequest(authToken).setRedirectUri(REDIRECT_URI) .execute(); credential = flow.createAndStoreCredential(response, "service"); store.store("service", credential); } catch (Exception e) { String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build(); throw new Exception("Authorization token expired, get a new one at " + url, e); } } else { String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build(); throw new Exception("Application must be authorized at " + url); } } } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:com.github.lbroudoux.elasticsearch.river.drive.rest.DriveOAuthAction.java
License:Apache License
@Override public void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { if (logger.isDebugEnabled()) { logger.debug("REST DriveOAuthAction called"); }/* w w w . j a v a2s .com*/ String clientId = request.param("client_id"); String clientSecret = request.param("client_secret"); String authCode = request.param("auth_code"); String authCode1 = request.param("auth_code_1"); if (clientId == null || clientSecret == null) { onFailure(request, channel, new IOException("client_id and client_secret can not be null.")); } try { XContentBuilder builder = jsonBuilder(); // We'll use some transport and json factory for sure. HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); if (authCode == null) { // It's the first call, we've got to build the authorization url. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientId, clientSecret, Arrays.asList(DriveScopes.DRIVE_READONLY)) .setAccessType("offline").setApprovalPrompt("force").build(); builder.startObject() .field(new XContentBuilderString("url"), flow.newAuthorizationUrl().setRedirectUri("urn:ietf:wg:oauth:2.0:oob").build()) .endObject(); } else { // We've got auth code from Google and should request an access token and a refresh token. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientId, clientSecret, Arrays.asList(DriveScopes.DRIVE_READONLY)) .setAccessType("offline").setApprovalPrompt("force").build(); // authCode main contain a "/"; recreate it if splitted. if (authCode1 != null) { authCode = authCode + "/" + authCode1; } GoogleTokenResponse response = flow.newTokenRequest(authCode) .setRedirectUri("urn:ietf:wg:oauth:2.0:oob").execute(); builder.startObject().field(new XContentBuilderString("accessToken"), response.getAccessToken()) .field(new XContentBuilderString("refreshToken"), response.getRefreshToken()).endObject(); } channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder)); } catch (IOException ioe) { onFailure(request, channel, ioe); } }