Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeTokenRequest setRedirectUri

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeTokenRequest setRedirectUri

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeTokenRequest setRedirectUri.

Prototype

@Override
    public GoogleAuthorizationCodeTokenRequest setRedirectUri(String redirectUri) 

Source Link

Usage

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  av  a 2  s.co 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   w  ww .ja  va 2s .  c  om
        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  av  a 2 s .c  o 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.");
                }/*w  w  w .  j a va  2s .c  om*/

                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.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 v  a  2  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: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);
}