List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeTokenRequest execute
@Override public GoogleTokenResponse execute() throws IOException
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: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 {// w w w . j a v a2 s . c o m 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.liferay.google.GoogleOAuth.java
License:Open Source License
protected Credential exchangeCode(long companyId, String authorizationCode, String redirectUri) throws CodeExchangeException, SystemException { try {/*from ww w . ja va 2 s. c o m*/ GoogleAuthorizationCodeFlow flow = getFlow(companyId); GoogleAuthorizationCodeTokenRequest token = flow.newTokenRequest(authorizationCode); token.setRedirectUri(redirectUri); GoogleTokenResponse response = token.execute(); return flow.createAndStoreCredential(response, null); } catch (IOException e) { System.err.println("An error occurred: " + e); throw new CodeExchangeException(); } }
From source file:com.liferay.google.login.hook.action.GoogleLoginAction.java
License:Open Source License
protected Credential getCredential(long companyId, String authorizationCode, String redirectURI) throws Exception { GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = getGoogleAuthorizationCodeFlow(companyId); GoogleAuthorizationCodeTokenRequest googleAuthorizationCodeTokenRequest = googleAuthorizationCodeFlow .newTokenRequest(authorizationCode); googleAuthorizationCodeTokenRequest.setRedirectUri(redirectURI); GoogleTokenResponse googleTokenResponse = googleAuthorizationCodeTokenRequest.execute(); return googleAuthorizationCodeFlow.createAndStoreCredential(googleTokenResponse, null); }
From source file:com.liferay.portal.security.sso.google.internal.GoogleAuthorizationImpl.java
License:Open Source License
@Override public User addOrUpdateUser(HttpSession session, long companyId, String authorizationCode, String returnRequestUri, List<String> scopes) throws Exception { GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = getGoogleAuthorizationCodeFlow(companyId, scopes); GoogleAuthorizationCodeTokenRequest googleAuthorizationCodeTokenRequest = googleAuthorizationCodeFlow .newTokenRequest(authorizationCode); googleAuthorizationCodeTokenRequest.setRedirectUri(returnRequestUri); GoogleTokenResponse googleTokenResponse = googleAuthorizationCodeTokenRequest.execute(); Credential credential = googleAuthorizationCodeFlow.createAndStoreCredential(googleTokenResponse, null); Userinfoplus userinfoplus = getUserinfoplus(credential); if (userinfoplus == null) { return null; }/*from w w w .j a v a 2 s . co m*/ ServiceBeanMethodInvocationFactoryUtil.proceed(this, GoogleAuthorizationImpl.class, _doAddOrUpdateUser, new Object[] { session, companyId, userinfoplus }, new String[] { "transactionAdvice" }); return doAddOrUpdateUser(session, companyId, userinfoplus); }
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."); }/* www . j av a 2 s. com*/ 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:org.sociotech.communitymashup.source.google.urlshortener.authorization.GoogleOAuth20AuthorizationServlet.java
License:Open Source License
@Override public boolean finishAuthorizationWithCode(String callbackCode) { GoogleTokenResponse googleToken;//w w w .java 2s . c o m // finish authorization try { // get property values from configuration String clientID = sourceConfiguration.getPropertyValue(GoogleUrlShortenerProperties.CLIENT_ID_PROPERTY); String clientSecret = sourceConfiguration .getPropertyValue(GoogleUrlShortenerProperties.CLIENT_SECRET_PROPERTY); String redirectUri = sourceConfiguration.getPropertyValueElseDefault( GoogleUrlShortenerProperties.REDIRECT_URI_PROPERTY, GoogleUrlShortenerProperties.REDIRECT_URI_DEFAULT); GoogleAuthorizationCodeTokenRequest tokenRequest = new GoogleAuthorizationCodeTokenRequest( new NetHttpTransport(), new JacksonFactory(), clientID, clientSecret, callbackCode, redirectUri); // execute request googleToken = tokenRequest.execute(); } catch (IOException e) { // not successful return false; } if (googleToken == null || googleToken.getAccessToken() == null || googleToken.getAccessToken().isEmpty()) { // Got no access token return false; } // calc expiration time Long expirationTime = System.currentTimeMillis() + 1000 * googleToken.getExpiresInSeconds(); //System.out.println("Access Token: " + googleToken.getAccessToken()); // keep source state SourceState sourceState = sourceConfiguration.getState(); // stop source for changes sourceConfiguration.setState(SourceState.STOPED); // store access token and make it unchangeable sourceConfiguration.addProperty(GoogleUrlShortenerProperties.ACCESS_TOKEN_PROPERTY, googleToken.getAccessToken()); Property accessTokenProperty = sourceConfiguration .getProperty(GoogleUrlShortenerProperties.ACCESS_TOKEN_PROPERTY); accessTokenProperty.setChangeable(false); // store access token expiration date and make it unchangeable sourceConfiguration.addProperty(GoogleUrlShortenerProperties.ACCESS_TOKEN_EXPIRATION_PROPERTY, "" + expirationTime); Property accessTokenExpirationProperty = sourceConfiguration .getProperty(GoogleUrlShortenerProperties.ACCESS_TOKEN_EXPIRATION_PROPERTY); accessTokenExpirationProperty.setChangeable(false); // store refresh token and make it unchangeable sourceConfiguration.addProperty(GoogleUrlShortenerProperties.REFRESH_TOKEN_PROPERTY, googleToken.getRefreshToken()); Property refreshTokenProperty = sourceConfiguration .getProperty(GoogleUrlShortenerProperties.REFRESH_TOKEN_PROPERTY); refreshTokenProperty.setChangeable(false); // reactivate source sourceConfiguration.setState(sourceState); // TODO unregister and cleanup return true; }
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 w w . j a va 2s .c om * @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); }