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:org.gameontext.auth.google.GoogleAuth.java

License:Apache License

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport httpTransport = new NetHttpTransport();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(httpTransport, jsonFactory, key, secret,
            Arrays.asList("https://www.googleapis.com/auth/userinfo.profile",
                    "https://www.googleapis.com/auth/userinfo.email"));

    try {/* ww w  .  ja  v  a 2 s  . co m*/
        // google will tell the users browser to go to this address once
        // they are done authing.
        String callbackURL = authURL + "/GoogleCallback";
        request.getSession().setAttribute("google", flow);

        String authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(callbackURL).build();
        Log.log(Level.FINEST, this, "Google Auth with callback: {0}", authorizationUrl);

        // send the user to google to be authenticated.
        response.sendRedirect(authorizationUrl);

    } catch (Exception e) {
        throw new ServletException(e);
    }

}

From source file:org.vx68k.hudson.plugin.google.login.GoogleLoginService.java

License:Open Source License

/**
 * Handles a federated login request.// w ww . j a  va  2s.c  o  m
 *
 * @param request HTTP servlet request
 * @param from URL path where the login request made
 * @return HTTP response for the request
 */
public HttpResponse doLogin(HttpServletRequest request, @QueryParameter String from) {
    GoogleLoginServiceProperty.Descriptor descriptor = getHudson()
            .getDescriptorByType(GoogleLoginServiceProperty.Descriptor.class);

    HttpSession session = request.getSession();
    session.removeAttribute(LOGIN_FROM_NAME);
    if (from != null) {
        String contextPath = request.getContextPath();
        // Handling a path that is not prefixed by the context path.
        if (!from.startsWith(contextPath)) {
            from = contextPath + from;
        }
        if (!from.equals(contextPath + "/login")) {
            session.setAttribute(LOGIN_FROM_NAME, from);
        }
    }

    GoogleAuthorizationCodeFlow flow = descriptor.getAuthorizationCodeFlow();
    GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
    url.setRedirectUri(getRedirectUri());
    url.setState(session.getId());
    return HttpResponses.redirectTo(url.build());
}

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(//w  ww . j  a va  2s.  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   ww w . j  av a  2s . c o 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  a  v  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);
}