Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleClientSecrets load

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleClientSecrets load

Introduction

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

Prototype

public static GoogleClientSecrets load(JsonFactory jsonFactory, Reader reader) throws IOException 

Source Link

Document

Loads the client_secrets.json file from the given reader.

Usage

From source file:secureemailclient.applet.GmailAuth.java

public static String obtainAuthUrl() throws IOException {
    if (authUrl != null) {
        return authUrl;
    }// ww w.  j  ava  2s  .c o m

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

    clientSecrets = GoogleClientSecrets.load(jsonFactory, new StringReader(CLIENT_SECRET_JSON));

    // Allow user to authorize via url.
    flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets,
            Arrays.asList(SCOPE)).setAccessType("online").setApprovalPrompt("auto").build();

    authUrl = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build();

    return authUrl;
}

From source file:sync.GoogleCalendar.java

License:Apache License

public static Credential authorize(final HttpTransport httpTransport,
        final FileDataStoreFactory dataStoreFactory, final JsonFactory JSON_FACTORY) throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(new FileInputStream(new File("client_secret_google.json"))));

    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
                    .build();/*from   w w  w. j a  va 2s  .  c  o m*/

    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

From source file:to.flows.googledrive.CredentialMediator.java

License:Apache License

/**
 * Creates a new CredentialsManager for the given HTTP request.
 *
 * @param request Request in which session credentials are stored.
 * @param clientSecretsStream Stream of client_secrets.json.
 * @throws InvalidClientSecretsException
 *///from   ww  w  . j  a  va2 s. c om
public CredentialMediator(HttpServletRequest request, InputStream clientSecretsStream,
        Collection<String> scopes) throws InvalidClientSecretsException {
    this.request = request;
    this.scopes = scopes;
    //this.credentialStore = new AppEngineCredentialStore();
    // this.credentialStore = new MemoryBasedCredentialStore();
    this.credentialStore = JDOPersistenceHelper.createJDOCredentialStore();
    try {
        secrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretsStream);
    } catch (IOException e) {
        throw new InvalidClientSecretsException("client_secrets.json is missing or invalid.");
    }
}

From source file:to.lean.tools.gmail.importer.gmail.Authorizer.java

License:Open Source License

private GoogleClientSecrets loadGoogleClientSecrets(JsonFactory jsonFactory) throws IOException {
    URL url = Resources.getResource("client_secret.json");
    CharSource inputSupplier = Resources.asCharSource(url, Charsets.UTF_8);
    return GoogleClientSecrets.load(jsonFactory, inputSupplier.openStream());
}

From source file:twitter.api.YoutubeResearch.java

License:Apache License

/**
 * Initialize a YouTube object to search for videos on YouTube. Then
 * display the name and thumbnail image of each video in the result set.
 *
 *///from   ww  w  .  ja  v  a2 s .  co  m
private static Credential authorize(List<String> scopes) throws Exception {

    InputStream inputStream = new FileInputStream("/tmp/client_secrets.json");
    System.out.println(inputStream);
    Reader reader = new InputStreamReader(inputStream);
    // Load client secrets.
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(new JacksonFactory(), reader);

    // Checks that the defaults have been replaced (Default = "Enter X here").
    //        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
    //                || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
    //            System.err.println(
    //                    "Enter Client ID and Secret from https://code.google.com/apis/console/?api=youtube"
    //                            + "into youtube-analytics-cmdline-report-sample/src/main/resources/client_secrets.json");
    //            System.exit(1);
    //        }

    // Set up file credential store.
    FileCredentialStore credentialStore = new FileCredentialStore(
            new File(System.getProperty("user.home"), ".credentials/youtube-analytics-api-report.json"),
            new JacksonFactory());

    // Set up authorization code flow.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(new NetHttpTransport(),
            new JacksonFactory(), clientSecrets, scopes).setCredentialStore(credentialStore).build();

    // Authorize.
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

From source file:ubicrypt.core.provider.gdrive.GDriveAuthorizer.java

License:Open Source License

private static GoogleClientSecrets appCredentials() throws IOException {
    return GoogleClientSecrets.load(getDefaultInstance(),
            new InputStreamReader(GDriveAuthorizer.class.getResourceAsStream("/google.json")));
}

From source file:ubicrypt.core.provider.gdrive.GDriveProvider.java

License:Open Source License

private static GoogleClientSecrets appCredentials() throws IOException {
    return GoogleClientSecrets.load(getDefaultInstance(),
            new InputStreamReader(GDriveProvider.class.getResourceAsStream("/google.json")));
}

From source file:uk.ac.cam.cl.dtg.segue.auth.GoogleAuthenticator.java

License:Apache License

/**
 * Construct a google authenticator.//from w  ww  .j  av a  2 s.  c o m
 * 
 * @param clientSecretLocation
 *            - external file containing the secret provided by the google service.
 * @param callbackUri
 *            - The allowed URI for callbacks as registered with google.
 * @param requestedScopes
 *            - The scopes that will be granted to Segue.
 * @throws IOException
 *             - if we cannot load the secret file.
 */
@Inject
public GoogleAuthenticator(@Named(Constants.GOOGLE_CLIENT_SECRET_LOCATION) final String clientSecretLocation,
        @Named(Constants.GOOGLE_CALLBACK_URI) final String callbackUri,
        @Named(Constants.GOOGLE_OAUTH_SCOPES) final String requestedScopes) throws IOException {
    this.jsonFactory = new JacksonFactory();
    this.httpTransport = new NetHttpTransport();

    Validate.notBlank(clientSecretLocation, "Missing resource %s", clientSecretLocation);

    // load up the client secrets from the file system.
    InputStream inputStream = new FileInputStream(clientSecretLocation);
    InputStreamReader isr = new InputStreamReader(inputStream);

    clientSecrets = GoogleClientSecrets.load(new JacksonFactory(), isr);

    this.requestedScopes = Arrays.asList(requestedScopes.split(";"));
    this.callbackUri = callbackUri;

    if (null == credentialStore) {
        credentialStore = CacheBuilder.newBuilder()
                .expireAfterAccess(CREDENTIAL_CACHE_TTL_MINUTES, TimeUnit.MINUTES).<String, Credential>build();
    }

    if (null == tokenVerifier) {
        tokenVerifier = new GoogleIdTokenVerifier(httpTransport, jsonFactory);
    }
}

From source file:uk.co.inetria.pi.app.CmdLineAuthenticationProvider.java

License:Apache License

/**
 * Create an instance of Credential/*from   www.ja v a2  s  .  co m*/
 * @return
 * @throws IOException
 */
protected Credential getCredential() throws IOException {

    if (this.clientSecretsFile == null) {
        throw new IllegalArgumentException("client secrets file is required");
    }

    if (this.scopes == null) {
        throw new IllegalArgumentException("you need to provide at least one scope");
    }

    // initialize the transport
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    } catch (GeneralSecurityException e) {
        log.log(Level.SEVERE, "failed to create transport", e);
        throw new IOException(e);
    }

    // initialize the data store factory
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(getClass().getClassLoader().getResourceAsStream(this.clientSecretsFile)));

    // Set up authorization code flow.

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();

    // authorize, this will prompt the user to enter a url on their browser then paste the code 
    return new AuthorizationCodeInstalledApp(flow, new PromptReceiver()).authorize("user");

    // the line below will expect you to have some way to browse to the URL locally, not useful when you 
    // are running a Pi through SSH
    // return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

From source file:uk.co.unclealex.googleauth.GoogleOauthFilter.java

License:Apache License

/**
 * Loads the authorization code flow to be used across all HTTP servlet
 * requests (only called during the first HTTP servlet request).
 *//*from   w  ww .j a v  a  2s  . com*/
protected AuthorizationCodeFlow loadFlow(HttpSession session) throws ServletException, IOException {
    AuthorizationCodeFlow flow = (AuthorizationCodeFlow) session.getAttribute(FLOW);
    if (flow == null) {
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(getJsonFactory(),
                getClass().getClassLoader().getResourceAsStream(getClientSecretsResourceName()));
        Set<String> scopes = new HashSet<String>(
                Arrays.asList(Oauth2Scopes.USERINFO_EMAIL, Oauth2Scopes.USERINFO_PROFILE));
        List<String> extraScopes = getExtraScopes();
        if (extraScopes != null) {
            scopes.addAll(extraScopes);
        }
        flow = createAuthorizationCodeFlowBuilder(clientSecrets, scopes)
                .setCredentialStore(new MemoryCredentialStore()).build();
        session.setAttribute(FLOW, flow);
    }
    return flow;
}