本文整理汇总了Java中com.google.auth.oauth2.GoogleCredentials类的典型用法代码示例。如果您正苦于以下问题:Java GoogleCredentials类的具体用法?Java GoogleCredentials怎么用?Java GoogleCredentials使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
GoogleCredentials类属于com.google.auth.oauth2包,在下文中一共展示了GoogleCredentials类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testVerifyIdTokenWithExplicitProjectId
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
@Test
public void testVerifyIdTokenWithExplicitProjectId() throws Exception {
GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines.getCredentials(firebaseOptions);
Assume.assumeFalse(
"Skipping testVerifyIdTokenWithExplicitProjectId for service account credentials",
credentials instanceof ServiceAccountCredentials);
FirebaseOptions options =
new FirebaseOptions.Builder(firebaseOptions)
.setProjectId("mock-project-id")
.build();
FirebaseApp app = FirebaseApp.initializeApp(options, "testVerifyIdTokenWithExplicitProjectId");
try {
FirebaseAuth.getInstance(app).verifyIdTokenAsync("foo").get();
fail("Expected exception.");
} catch (ExecutionException expected) {
Assert.assertNotEquals(
"com.google.firebase.FirebaseException: Must initialize FirebaseApp with a project ID "
+ "to call verifyIdToken()",
expected.getMessage());
assertTrue(expected.getCause() instanceof IllegalArgumentException);
}
}
示例2: getProjectId
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
/**
* Returns the Google Cloud project ID associated with this app.
*
* @return A string project ID or null.
*/
@Nullable
String getProjectId() {
// Try to get project ID from user-specified options.
String projectId = options.getProjectId();
// Try to get project ID from the credentials.
if (Strings.isNullOrEmpty(projectId)) {
GoogleCredentials credentials = options.getCredentials();
if (credentials instanceof ServiceAccountCredentials) {
projectId = ((ServiceAccountCredentials) credentials).getProjectId();
}
}
// Try to get project ID from the environment.
if (Strings.isNullOrEmpty(projectId)) {
projectId = System.getenv("GCLOUD_PROJECT");
}
return projectId;
}
示例3: setUpClass
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
@BeforeClass
public static void setUpClass() throws IOException {
// Init app with non-admin privileges
Map<String, Object> auth = MapBuilder.of("uid", "my-service-worker");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(
IntegrationTestUtils.getServiceAccountCertificate()))
.setDatabaseUrl(IntegrationTestUtils.getDatabaseUrl())
.setDatabaseAuthVariableOverride(auth)
.build();
masterApp = FirebaseApp.initializeApp(options, "RulesTestIT");
List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
reader = refs.get(0);
writer = refs.get(1);
String rules = JsonMapper.serializeJson(
MapBuilder.of("rules", MapBuilder.of(writer.getKey(), testRules)));
uploadRules(rules);
TestHelpers.waitForRoundtrip(writer.getRoot());
}
示例4: createApplicationDefaultCredential
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
private static GoogleCredentials createApplicationDefaultCredential() throws IOException {
final MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
// Set the GOOGLE_APPLICATION_CREDENTIALS environment variable for application-default
// credentials. This requires us to write the credentials to the location specified by the
// environment variable.
File credentialsFile = File.createTempFile("google-test-credentials", "json");
PrintWriter writer = new PrintWriter(Files.newBufferedWriter(credentialsFile.toPath(), UTF_8));
writer.print(ServiceAccount.EDITOR.asString());
writer.close();
Map<String, String> environmentVariables =
ImmutableMap.<String, String>builder()
.put("GOOGLE_APPLICATION_CREDENTIALS", credentialsFile.getAbsolutePath())
.build();
TestUtils.setEnvironmentVariables(environmentVariables);
credentialsFile.deleteOnExit();
return GoogleCredentials.getApplicationDefault(new HttpTransportFactory() {
@Override
public HttpTransport create() {
return transport;
}
});
}
示例5: createRefreshTokenCredential
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
private static GoogleCredentials createRefreshTokenCredential() throws IOException {
final MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addClient(CLIENT_ID, CLIENT_SECRET);
transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN);
Map<String, Object> secretJson = new HashMap<>();
secretJson.put("client_id", CLIENT_ID);
secretJson.put("client_secret", CLIENT_SECRET);
secretJson.put("refresh_token", REFRESH_TOKEN);
secretJson.put("type", "authorized_user");
InputStream refreshTokenStream =
new ByteArrayInputStream(JSON_FACTORY.toByteArray(secretJson));
return UserCredentials.fromStream(refreshTokenStream, new HttpTransportFactory() {
@Override
public HttpTransport create() {
return transport;
}
});
}
示例6: testServiceAccountRequired
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
@Test
public void testServiceAccountRequired() throws Exception {
GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines.getCredentials(firebaseOptions);
Assume.assumeFalse("Skipping testServiceAccountRequired for service account credentials",
credentials instanceof ServiceAccountCredentials);
FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "testServiceAccountRequired");
try {
FirebaseAuth.getInstance(app).createCustomTokenAsync("foo").get();
fail("Expected exception.");
} catch (IllegalStateException expected) {
Assert.assertEquals(
"Must initialize FirebaseApp with a service account credential to call "
+ "createCustomToken()",
expected.getMessage());
}
}
示例7: testAppDelete
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
@Test
public void testAppDelete() throws IOException {
FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
.setStorageBucket("mock-bucket-name")
.build());
assertNotNull(StorageClient.getInstance());
assertNotNull(StorageClient.getInstance(app));
app.delete();
try {
StorageClient.getInstance(app);
fail("No error thrown for deleted app");
} catch (IllegalStateException expected) {
// ignore
}
}
示例8: createOptionsWithOnlyMandatoryValuesSet
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
@Test
public void createOptionsWithOnlyMandatoryValuesSet() throws IOException, InterruptedException {
FirebaseOptions firebaseOptions =
new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
.build();
assertNotNull(firebaseOptions.getJsonFactory());
assertNotNull(firebaseOptions.getHttpTransport());
assertNotNull(firebaseOptions.getThreadManager());
assertNull(firebaseOptions.getDatabaseUrl());
assertNull(firebaseOptions.getStorageBucket());
GoogleCredentials credentials = firebaseOptions.getCredentials();
assertNotNull(credentials);
assertTrue(credentials instanceof ServiceAccountCredentials);
assertEquals(
GoogleCredential.fromStream(ServiceAccount.EDITOR.asStream()).getServiceAccountId(),
((ServiceAccountCredentials) credentials).getClientEmail());
}
示例9: createOptionsWithFirebaseCredential
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
@Test
public void createOptionsWithFirebaseCredential() throws IOException {
FirebaseOptions firebaseOptions =
new FirebaseOptions.Builder()
.setCredential(FirebaseCredentials.fromCertificate(ServiceAccount.EDITOR.asStream()))
.build();
assertNotNull(firebaseOptions.getJsonFactory());
assertNotNull(firebaseOptions.getHttpTransport());
assertNull(firebaseOptions.getDatabaseUrl());
assertNull(firebaseOptions.getStorageBucket());
GoogleCredentials credentials = firebaseOptions.getCredentials();
assertNotNull(credentials);
assertTrue(credentials instanceof ServiceAccountCredentials);
assertEquals(
GoogleCredential.fromStream(ServiceAccount.EDITOR.asStream()).getServiceAccountId(),
((ServiceAccountCredentials) credentials).getClientEmail());
}
示例10: createOptionsWithCustomFirebaseCredential
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
@Test
public void createOptionsWithCustomFirebaseCredential() throws IOException {
FirebaseOptions firebaseOptions =
new FirebaseOptions.Builder()
.setCredential(new FirebaseCredential() {
@Override
public Task<GoogleOAuthAccessToken> getAccessToken() {
return null;
}
})
.build();
assertNotNull(firebaseOptions.getJsonFactory());
assertNotNull(firebaseOptions.getHttpTransport());
assertNull(firebaseOptions.getDatabaseUrl());
assertNull(firebaseOptions.getStorageBucket());
GoogleCredentials credentials = firebaseOptions.getCredentials();
assertNotNull(credentials);
}
示例11: getApplicationDefaultCredentials
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
/**
* Ensures initialization of Google Application Default Credentials. Any test that depends on
* ADC should consider this as a fixture, and invoke it before hand. Since ADC are initialized
* once per JVM, this makes sure that all dependent tests get the same ADC instance, and
* can reliably reason about the tokens minted using it.
*/
public static synchronized GoogleCredentials getApplicationDefaultCredentials()
throws IOException {
if (defaultCredentials != null) {
return defaultCredentials;
}
final MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), TEST_ADC_ACCESS_TOKEN);
File serviceAccount = new File("src/test/resources/service_accounts", "editor.json");
Map<String, String> environmentVariables =
ImmutableMap.<String, String>builder()
.put("GOOGLE_APPLICATION_CREDENTIALS", serviceAccount.getAbsolutePath())
.build();
setEnvironmentVariables(environmentVariables);
defaultCredentials = GoogleCredentials.getApplicationDefault(new HttpTransportFactory() {
@Override
public HttpTransport create() {
return transport;
}
});
return defaultCredentials;
}
示例12: getCredentialsFromFile
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
public static GoogleCredentials getCredentialsFromFile(String credentialsPath) throws IOException
{
if (credentialsPath == null || credentialsPath.length() == 0)
throw new IllegalArgumentException("credentialsPath may not be null or empty");
GoogleCredentials credentials = null;
File credentialsFile = new File(credentialsPath);
if (!credentialsFile.isFile())
{
throw new IOException(
String.format("Error reading credential file %s: File does not exist", credentialsPath));
}
try (InputStream credentialsStream = new FileInputStream(credentialsFile))
{
credentials = GoogleCredentials.fromStream(credentialsStream, CloudSpannerOAuthUtil.HTTP_TRANSPORT_FACTORY);
}
return credentials;
}
示例13: CloudSpannerIT
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
public CloudSpannerIT()
{
// generate a unique instance id for this test run
Random rnd = new Random();
this.instanceId = "test-instance-" + rnd.nextInt(1000000);
this.credentialsPath = "cloudspanner-key.json";
this.projectId = CloudSpannerConnection.getServiceAccountProjectId(credentialsPath);
GoogleCredentials credentials = null;
try
{
credentials = CloudSpannerConnection.getCredentialsFromFile(credentialsPath);
}
catch (IOException e)
{
throw new RuntimeException("Could not read key file " + credentialsPath, e);
}
Builder builder = SpannerOptions.newBuilder();
builder.setProjectId(projectId);
builder.setCredentials(credentials);
SpannerOptions options = builder.build();
spanner = options.getService();
}
示例14: GcpPubSubAutoConfiguration
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
public GcpPubSubAutoConfiguration(GcpPubSubProperties gcpPubSubProperties,
GcpProjectIdProvider gcpProjectIdProvider,
CredentialsProvider credentialsProvider) throws IOException {
this.gcpPubSubProperties = gcpPubSubProperties;
this.finalProjectIdProvider = gcpPubSubProperties.getProjectId() != null
? gcpPubSubProperties::getProjectId
: gcpProjectIdProvider;
this.finalCredentialsProvider = gcpPubSubProperties.getCredentials().getLocation() != null
? FixedCredentialsProvider.create(
GoogleCredentials.fromStream(
gcpPubSubProperties.getCredentials().getLocation().getInputStream())
.createScoped(gcpPubSubProperties.getCredentials().getScopes()))
: credentialsProvider;
}
示例15: onPostExecute
import com.google.auth.oauth2.GoogleCredentials; //导入依赖的package包/类
@Override
protected void onPostExecute(AccessToken accessToken) {
mAccessTokenTask = null;
final ManagedChannel channel = new OkHttpChannelProvider()
.builderForAddress(HOSTNAME, PORT)
.nameResolverFactory(new DnsNameResolverProvider())
.intercept(new GoogleCredentialsInterceptor(new GoogleCredentials(accessToken)
.createScoped(SCOPE)))
.build();
mApi = SpeechGrpc.newStub(channel);
// Schedule access token refresh before it expires
if (mHandler != null) {
mHandler.postDelayed(mFetchAccessTokenRunnable,
Math.max(accessToken.getExpirationTime().getTime()
- System.currentTimeMillis()
- ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE));
}
}