当前位置: 首页>>代码示例>>Java>>正文


Java Credential类代码示例

本文整理汇总了Java中com.google.api.client.auth.oauth2.Credential的典型用法代码示例。如果您正苦于以下问题:Java Credential类的具体用法?Java Credential怎么用?Java Credential使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Credential类属于com.google.api.client.auth.oauth2包,在下文中一共展示了Credential类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: authorize

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
/**
 * Authorizes the installed application to access user's protected data.
 *
 * @param scopes list of scopes needed to run youtube upload.
 * @param clientSecret the client secret from Google API console
 * @param credentialDatastore name of the credential datastore to cache OAuth tokens
 */
public static Credential authorize(
    Collection<String> scopes, String clientSecret, String credentialDatastore)
    throws IOException {
  // Load client secrets
  GoogleClientSecrets clientSecrets =
      GoogleClientSecrets.load(JSON_FACTORY, new StringReader(clientSecret));

  // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
  FileDataStoreFactory fileDataStoreFactory =
      new FileDataStoreFactory(new File(getCredentialsDirectory()));
  DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes)
          .setCredentialDataStore(datastore)
          .build();

  // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
开发者ID:youtube,项目名称:youtube-chat-for-minecraft,代码行数:28,代码来源:Auth.java

示例2: performRequest

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
private static void performRequest(String accessToken, String refreshToken, String apiKey, String apiSecret) throws GeneralSecurityException, IOException, MessagingException {
	HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
	JsonFactory jsonFactory = new JacksonFactory();
	final Credential credential = convertToGoogleCredential(accessToken, refreshToken, apiSecret, apiKey);
	Builder builder = new Gmail.Builder(httpTransport, jsonFactory, credential);
	builder.setApplicationName("OAuth API Sample");
	Gmail gmail = builder.build();
	MimeMessage content = createEmail("[email protected]", "[email protected]", "Test Email", "It works");
	Message message = createMessageWithEmail(content);
	gmail.users().messages().send("[email protected]", message).execute();
}
 
开发者ID:tburne,项目名称:blog-examples,代码行数:12,代码来源:ClientRequestAPI.java

示例3: getCredential

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
public final Credential getCredential() {
    if (googleCredential == null) {
        try {
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                    secureHttpTransport,
                    JacksonFactory.getDefaultInstance(),
                    googleSecrets,
                    requiredScopes)

                    .setAccessType("offline")
                    .setDataStoreFactory(new MemoryDataStoreFactory())
                    .build();

            googleCredential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
                    .authorize("user");

        } catch (IOException e) {
            //Will not occur
            logger.fatal(e);
            throw new RuntimeException();
        }
    }
    return googleCredential;
}
 
开发者ID:ViniciusArnhold,项目名称:ProjectAltaria,代码行数:25,代码来源:GoogleClientServiceFactory.java

示例4: authorize

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
/**
 * Authorizes the installed application to access user's protected data.
 */
public static void authorize(String userID, boolean driveAPI) throws IOException {
    // load client secrets

    // set up authorization code flow
    Collection<String> scopes = new ArrayList<String>();
    scopes.add(GamesScopes.GAMES);
    if (driveAPI)
        scopes.add(DriveScopes.DRIVE_APPDATA);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();
    // authorize
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()) {
        // Override open browser not working well on Linux and maybe other
        // OS.
        protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws java.io.IOException {
            Gdx.net.openURI(authorizationUrl.build());
        }
    }.authorize(userID);

    games = new Games.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(applicationName).build();
    if (driveAPI)
        drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(applicationName).build();

}
 
开发者ID:MrStahlfelge,项目名称:gdx-gamesvcs,代码行数:29,代码来源:GApiGateway.java

示例5: authorize

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static void authorize() throws IOException {
    // Load client secrets.
    InputStream in = Authorization.class.getClass().getResourceAsStream("/gallery/configs/client_id.json");
    GoogleClientSecrets clientSecrets =
        GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();
    
    Credential credential = new AuthorizationCodeInstalledApp(
        flow, new LocalServerReceiver()).authorize(NICK);
    
    System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    MAIN = credential;
}
 
开发者ID:Obsidiam,项目名称:joanne,代码行数:26,代码来源:Authorization.java

示例6: doLogin

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
public static void doLogin(String user){
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
        Credential credential = authorize(user);
        oauth2 = new Oauth2.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
        String picture = oauth2.userinfo().get().execute().getPicture();
        //name = oauth2.userinfo().get().execute().getName();
        downloadProfileImage(picture,user.toLowerCase());
        
  } catch (IOException e) {
    System.err.println(e.getMessage());
  } catch (Exception t) {

  }
}
 
开发者ID:Obsidiam,项目名称:amelia,代码行数:17,代码来源:AuthorizeGoogleUser.java

示例7: create

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
@Override
public Credential create() {
	// TODO(joaomartins): Consider supporting Spring Resources as credential locations. There
	// would need to be a way to create or inject a Spring context here statically, to load
	// the resource from there.
	String credentialResourceLocation = System.getProperty(CREDENTIAL_LOCATION_PROPERTY_NAME);
	if (credentialResourceLocation == null) {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug(CREDENTIAL_LOCATION_PROPERTY_NAME + " property does not exist. "
					+ "Socket factory will use application default credentials.");
		}
		return null;
	}

	try {
		return GoogleCredential.fromStream(new FileInputStream(credentialResourceLocation))
				.createScoped(Collections.singleton(GcpScope.SQLADMIN.getUrl()));
	}
	catch (IOException ioe) {
		LOGGER.warn("There was an error loading Cloud SQL credential.", ioe);
		return null;
	}
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:24,代码来源:SqlCredentialFactory.java

示例8: authorize

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws Exception 
 */
public static Credential authorize() throws Exception {
	// Load client secrets.
	InputStream in =
			SpreadsheetUtils.class.getResourceAsStream("/client_secret.json");
	GoogleClientSecrets clientSecrets =
			GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

	// Build flow and trigger user authorization request.
	GoogleAuthorizationCodeFlow flow =
			new GoogleAuthorizationCodeFlow.Builder(
					HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
			.setDataStoreFactory(DATA_STORE_FACTORY)
			.setAccessType("offline")
			.build();
	Credential credential = new AuthorizationCodeInstalledApp(
			flow, new LocalServerReceiver()).authorize("user");
	System.out.println(
			"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
	return credential;
}
 
开发者ID:axel-halin,项目名称:Thesis-JHipster,代码行数:26,代码来源:SpreadsheetUtils.java

示例9: authorize

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in =
            Login.class.getResourceAsStream("/client_secret.json");
    GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                    .setDataStoreFactory(DATA_STORE_FACTORY)
                    .setAccessType("offline")
                    .build();
    Credential credential = new AuthorizationCodeInstalledApp(
            flow, new LocalServerReceiver()).authorize("user");
    System.out.println(
            "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}
 
开发者ID:ashoknailwal,项目名称:desktop-gmail-client,代码行数:27,代码来源:Login.java

示例10: authorize

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws ResourceServerException Incorrect authorization
 */
public static Credential authorize() {
    // Load client secrets.
    final InputStream in =
            GoogleStorageServiceImpl.class.getResourceAsStream("/client_secret.json");
    Credential credential;
    try {
        final GoogleClientSecrets clientSecrets =
                GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        final GoogleAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow.Builder(
                        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                        .setDataStoreFactory(DATA_STORE_FACTORY)
                        .setAccessType("offline")
                        .build();
        credential = new AuthorizationCodeInstalledApp(
                flow, new LocalServerReceiver()).authorize("user");
    } catch (final IOException e) {
        throw new ResourceServerException("Incorrect authorization", e);
    }
    return credential;
}
 
开发者ID:JonkiPro,项目名称:REST-Web-Services,代码行数:29,代码来源:GoogleStorageServiceImpl.java

示例11: authorize

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
  // load client secrets
 Reader in = new FileReader("Local directory path for client_secrets.json file");
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, in);
  if (clientSecrets.getDetails().getClientId().startsWith("Your ")
      || clientSecrets.getDetails().getClientSecret().startsWith("Your ")) {
    System.out.println(
        "Enter Client ID and Secret from https://code.google.com/apis/console/?api=plus "
        + "into client_secrets.json");
    System.exit(1);
  }
  // set up authorization code flow
  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport, JSON_FACTORY, clientSecrets,
      Collections.singleton(PlusScopes.PLUS_ME)).setDataStoreFactory(
      dataStoreFactory).build();
  // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
开发者ID:sshubhadeep,项目名称:GooglePlusJavaImplementation,代码行数:21,代码来源:GooglePlusConsoleDisplay.java

示例12: authorize

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
/**
 * Creates a new authorized Credential object from a response token
 * @param token (String)
 * @param userId (String)
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize(String token, String userId) throws IOException
{
    // Load client secrets.
    InputStream in = new FileInputStream(Main.getBotSettingsManager().getGoogleOAuthSecret());
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = (new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES))
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();

    // remove any account previously associated with the token
    flow.getCredentialDataStore().delete(userId);

    // create the new credential
    GoogleTokenResponse response = flow.newTokenRequest(token)
            .setRedirectUri(clientSecrets.getDetails().getRedirectUris().get(0)).execute();
    return flow.createAndStoreCredential(response, userId);
}
 
开发者ID:notem,项目名称:Saber-Bot,代码行数:28,代码来源:GoogleAuth.java

示例13: getCredential

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
/**
 * retrieves credentials for a user if they exist,
 * if the user does not have credentials, use the default service account credentials
 * @param userID discord ID of user
 * @return credentials or null if IO error
 */
public static Credential getCredential(String userID)
{
    try
    {
        Credential credential = GoogleAuth.authorize(userID);
        if(credential == null)
        {
            credential = GoogleAuth.authorize();
        }
        return credential;
    }
    catch (IOException e)
    {
        return null;
    }
}
 
开发者ID:notem,项目名称:Saber-Bot,代码行数:23,代码来源:GoogleAuth.java

示例14: authorize

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
/***
 * Crates a Credential object authorized by the Google API.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException{
	InputStream in = CalendarAPI.class.getResourceAsStream("resources/client_secret.json");
   
	if(in == null) throw new IOException("Client information not found.");

	GoogleClientSecrets secrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(in));

	GoogleAuthorizationCodeFlow flow =
			new GoogleAuthorizationCodeFlow.Builder(
					http, jsonFactory, secrets, scopes)
					.setDataStoreFactory(dataFactory)
					.setAccessType("offline")
					.build();
	Credential cred = new AuthorizationCodeInstalledApp(
			flow, new LocalServerReceiver()).authorize("user");
	return cred;
}
 
开发者ID:beesenpai,项目名称:EVE,代码行数:23,代码来源:CalendarAPI.java

示例15: authorize

import com.google.api.client.auth.oauth2.Credential; //导入依赖的package包/类
public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {

        Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json"));
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
                || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
            System.out.println(
                    "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
                            + "into src/main/resources/client_secrets.json");
            System.exit(1);
        }

        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
        DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
                .build();

        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
    }
 
开发者ID:prakamya-mishra,项目名称:Shield,代码行数:25,代码来源:Auth.java


注:本文中的com.google.api.client.auth.oauth2.Credential类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。