Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newAuthorizationUrl

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newAuthorizationUrl

Introduction

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

Prototype

@Override
    public GoogleAuthorizationCodeRequestUrl newAuthorizationUrl() 

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:by.dev.madhead.gbp.tasks.gdrive.ObtainGoogleDriveTokensTask.java

License:Apache License

/**
 * Initiates Google Drive tokens obtaining flow.
 *//*from www.  j av a 2 s  .  c o m*/
@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

public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
    long companyId = themeDisplay.getCompanyId();

    String cmd = ParamUtil.getString(request, Constants.CMD);

    String redirectUri = PortalUtil.getPortalURL(request) + _REDIRECT_URI;

    if ("login".equals(cmd)) {
        GoogleAuthorizationCodeFlow flow = getFlow(companyId);

        GoogleAuthorizationCodeRequestUrl googleAuthorizationCodeRequestUrl = flow.newAuthorizationUrl();

        googleAuthorizationCodeRequestUrl.setRedirectUri(redirectUri);

        String url = googleAuthorizationCodeRequestUrl.build();

        response.sendRedirect(url);/* w ww .  ja v a  2 s .  c om*/
    } else if ("token".equals(cmd)) {
        HttpSession session = request.getSession();

        String code = ParamUtil.getString(request, "code");

        if (Validator.isNotNull(code)) {
            Credential credential = exchangeCode(companyId, code, redirectUri);

            Userinfoplus userinfo = getUserInfo(credential);

            User user = setGoogleCredentials(session, themeDisplay.getCompanyId(), userinfo);

            if ((user != null) && (user.getStatus() == WorkflowConstants.STATUS_INCOMPLETE)) {

                redirectUpdateAccount(request, response, user);

                return null;
            }

            PortletURL portletURL = PortletURLFactoryUtil.create(request, PortletKeys.FAST_LOGIN,
                    themeDisplay.getPlid(), PortletRequest.RENDER_PHASE);

            portletURL.setWindowState(LiferayWindowState.POP_UP);

            portletURL.setParameter("struts_action", "/login/login_redirect");

            response.sendRedirect(portletURL.toString());
        }
    }

    return null;
}

From source file:com.cloudglomerate.connection.OAuth2Native.java

License:Apache License

/**
 * Authorizes the installed application to access user's protected data.
 *
 * @param transport HTTP transport/*  ww w  .  ja v a2  s.  c  o m*/
 * @param jsonFactory JSON factory
 * @param receiver verification code receiver
 * @param scopes OAuth 2.0 scopes
 */
public static GoogleResponse authorize(HttpTransport transport, JsonFactory jsonFactory,
        Iterable<String> scopes) {

    String redirectUri = GoogleOAuthConstants.OOB_REDIRECT_URI;
    GoogleClientSecrets clientSecrets = null;
    try {
        clientSecrets = loadClientSecrets(jsonFactory);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    GoogleResponse gResp = new GoogleResponse(Status.INITIATED, Cloud.GOOGLE);
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory,
            clientSecrets, scopes).setAccessType("online").setApprovalPrompt("auto").build();

    gResp.setAuthCodeFlow(flow);

    String url = flow.newAuthorizationUrl().setRedirectUri(redirectUri).build();
    gResp.setURL(url);
    return gResp;
}

From source file:com.compguide.web.google.calendar.api.GoogleCalendar.java

/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException//from ww  w. j  av  a  2s.  c  o m
 */
public static Credential authorize() throws IOException {

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = authorizationCodeFlow("online");

    AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(RedirectURI);

    FacesContext.getCurrentInstance().getExternalContext().redirect(authorizationUrl.build());
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
            .authorize("user");
    return credential;
}

From source file:com.compguide.web.google.calendar.api.GoogleCalendar.java

/**
 * Creates URL for an authorization web page to allow the end user to
 * authorize the application.//from w w w  .  j a  v a  2  s  .c om
 *
 * @return an URL.
 * @throws IOException
 */
public static String authorizationRequest() throws IOException {

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = authorizationCodeFlow("online");

    AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(RedirectURI);

    return authorizationUrl.build();
}

From source file:com.example.plusPreviewAppengineSample.PlusSampleServlet.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // Check if we have stored credentials using the Authorization Flow.
    // Note that we only check if there are stored credentials, but not if they are still valid.
    // The user may have revoked authorization, in which case we would need to go through the
    // authorization flow again, which this implementation does not handle.
    GoogleAuthorizationCodeFlow authFlow = Utils.initializeFlow();
    Credential credential = authFlow.loadCredential(Utils.getUserId(req));
    if (credential == null) {
        // If we don't have a token in store, redirect to authorization screen.
        resp.sendRedirect(authFlow.newAuthorizationUrl().setRedirectUri(Utils.getRedirectUri(req)).build());
        return;/*from www  . j  av  a 2  s  . co  m*/
    }

    // If we do have stored credentials, build the Plus object using them.
    Plus plus = new Plus.Builder(Utils.HTTP_TRANSPORT, Utils.JSON_FACTORY, credential).setApplicationName("")
            .build();
    // Make the API call
    Person profile = null;
    try {
        profile = plus.people().get("me").execute();
    } catch (GoogleJsonResponseException e) {
        //The Authorization has been revoked so we must ask for it again
        authFlow.getCredentialStore().delete(Utils.getUserId(req), credential);
        resp.sendRedirect(authFlow.newAuthorizationUrl().setRedirectUri(Utils.getRedirectUri(req)).build());
        return;
    }
    // Send the results as the response
    PrintWriter respWriter = resp.getWriter();
    resp.setStatus(200);
    resp.setContentType("text/html");
    respWriter.println("<img src='" + profile.getImage().getUrl() + "'>");
    respWriter.println("<a href='" + profile.getUrl() + "'>" + profile.getDisplayName() + "</a>");
}

From source file:com.fredericvauchelles.ConnectMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException {

    try {//from   www  .  java 2s  .  c o m
        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);
    }

}