本文整理汇总了Java中com.google.auth.oauth2.AccessToken类的典型用法代码示例。如果您正苦于以下问题:Java AccessToken类的具体用法?Java AccessToken怎么用?Java AccessToken使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
AccessToken类属于com.google.auth.oauth2包,在下文中一共展示了AccessToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: start
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
/**
* Starts the TokenRefresher if not already started. Starts listening to credentials changed
* events, and schedules refresh events every time the OAuth2 token changes. If no active
* token is present, or if the available token is set to expire soon, this will also schedule
* a refresh event to be executed immediately.
*
* <p>This operation is idempotent. Calling it multiple times, or calling it after the
* refresher has been stopped has no effect.
*/
final synchronized void start() {
// Allow starting only from the ready state.
if (!state.compareAndSet(State.READY, State.STARTED)) {
return;
}
logger.debug("Starting the proactive token refresher");
credentials.addChangeListener(this);
AccessToken accessToken = credentials.getAccessToken();
long refreshDelay;
if (accessToken != null) {
// If the token is about to expire (i.e. expires in less than 5 minutes), schedule a
// refresh event with 0 delay. Otherwise schedule a refresh event at the regular token
// expiry time, minus 5 minutes.
refreshDelay = Math.max(getRefreshDelay(accessToken), 0L);
} else {
// If there is no token fetched so far, fetch one immediately.
refreshDelay = 0L;
}
scheduleRefresh(refreshDelay);
}
示例2: getToken
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
@Override
public void getToken(boolean forceRefresh, final GetTokenCompletionListener listener) {
try {
if (forceRefresh) {
credentials.refresh();
}
// The typical way to use a GoogleCredentials instance is to call its getRequestMetadata(),
// and include the metadata in your request. Since we are accessing the token directly via
// getAccessToken(), we must first call getRequestMetadata() to ensure the token is available
// (refreshed if necessary).
credentials.getRequestMetadata();
AccessToken accessToken = credentials.getAccessToken();
listener.onSuccess(wrapOAuthToken(accessToken, authVariable));
} catch (Exception e) {
listener.onError(e.toString());
}
}
示例3: onChanged
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
@Override
public void onChanged(OAuth2Credentials credentials) throws IOException {
// When this event fires, it is guaranteed that credentials.getAccessToken() will return a
// valid OAuth2 token.
final AccessToken accessToken = credentials.getAccessToken();
// Notify the TokenChangeListener on database's thread pool to make sure that
// all database work happens on database worker threads.
executor.execute(
new Runnable() {
@Override
public void run() {
listener.onTokenChange(wrapOAuthToken(accessToken, authVariable));
}
});
}
示例4: testGetTokenError
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
@Test
public void testGetTokenError() throws InterruptedException {
MockGoogleCredentials credentials = new MockGoogleCredentials("mock-token") {
@Override
public AccessToken refreshAccessToken() throws IOException {
throw new RuntimeException("Test error");
}
};
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(credentials)
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
JvmAuthTokenProvider provider = new JvmAuthTokenProvider(app, DIRECT_EXECUTOR);
TestGetTokenListener listener = new TestGetTokenListener();
provider.getToken(true, listener);
assertEquals("java.lang.RuntimeException: Test error", listener.get());
}
示例5: onPostExecute
import com.google.auth.oauth2.AccessToken; //导入依赖的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));
}
}
示例6: getGoogleCloudRecognition
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
/**
* Utility method to construct the {@link RecognitionGoogleCloud} instance
*
* @param recognitionListener the {@link RecognitionListener}
* @return the {@link RecognitionGoogleCloud} instance
*/
public RecognitionGoogleCloud getGoogleCloudRecognition(@NonNull final RecognitionMic recogMic,
@NonNull final SaiyRecognitionListener recognitionListener) {
if (DEBUG) {
MyLog.i(CLS_NAME, "getGoogleCloudRecognition");
}
if (servingRemote()) {
return new RecognitionGoogleCloud(mContext, recognitionListener,
getCallback().getParcel().getVRLanguageGoogle(),
new AccessToken(getCallback().getParcel().getGOOGLE_CLOUD_ACCESS_TOKEN(),
new Date(System.currentTimeMillis()
+ getCallback().getParcel().getGOOGLE_CLOUD_ACCESS_EXPIRY())),
recogMic);
} else {
return new RecognitionGoogleCloud(mContext, recognitionListener,
VRLanguageGoogle.getLanguage(getVRLocale()), GoogleConfiguration.ACCESS_TOKEN, recogMic);
}
}
示例7: oauth2AuthToken
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
/** Sends a unary rpc with raw oauth2 access token credentials. */
public void oauth2AuthToken(String jsonKey, InputStream credentialsStream, String authScope)
throws Exception {
GoogleCredentials utilCredentials =
GoogleCredentials.fromStream(credentialsStream);
utilCredentials = utilCredentials.createScoped(Arrays.<String>asList(authScope));
AccessToken accessToken = utilCredentials.refreshAccessToken();
OAuth2Credentials credentials = OAuth2Credentials.create(accessToken);
TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
.withCallCredentials(MoreCallCredentials.from(credentials));
final SimpleRequest request = SimpleRequest.newBuilder()
.setFillUsername(true)
.setFillOauthScope(true)
.build();
final SimpleResponse response = stub.unaryCall(request);
assertFalse(response.getUsername().isEmpty());
assertTrue("Received username: " + response.getUsername(),
jsonKey.contains(response.getUsername()));
assertFalse(response.getOauthScope().isEmpty());
assertTrue("Received oauth scope: " + response.getOauthScope(),
authScope.contains(response.getOauthScope()));
}
示例8: testWithOAuth2Credential
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
@Test
public void testWithOAuth2Credential() {
final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
final OAuth2Credentials oAuth2Credentials = new OAuth2Credentials() {
@Override
public AccessToken refreshAccessToken() throws IOException {
return token;
}
};
interceptor = new ClientAuthInterceptor(oAuth2Credentials, executor);
ClientCall<String, Integer> interceptedCall =
interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
Metadata headers = new Metadata();
interceptedCall.start(listener, headers);
assertEquals(listener, call.responseListener);
assertEquals(headers, call.headers);
Iterable<String> authorization = headers.getAll(AUTHORIZATION);
Assert.assertArrayEquals(new String[]{"Bearer allyourbase"},
Iterables.toArray(authorization, String.class));
}
示例9: oauth2Credential
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
@Test
public void oauth2Credential() {
final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
final OAuth2Credentials credentials = new OAuth2Credentials() {
@Override
public AccessToken refreshAccessToken() throws IOException {
return token;
}
};
GoogleAuthLibraryCallCredentials callCredentials =
new GoogleAuthLibraryCallCredentials(credentials);
callCredentials.applyRequestMetadata(method, attrs, executor, applier);
assertEquals(1, runPendingRunnables());
verify(applier).apply(headersCaptor.capture());
Metadata headers = headersCaptor.getValue();
Iterable<String> authorization = headers.getAll(AUTHORIZATION);
assertArrayEquals(new String[]{"Bearer allyourbase"},
Iterables.toArray(authorization, String.class));
}
示例10: serviceAccountToJwt
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
@Test
public void serviceAccountToJwt() throws Exception {
KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
@SuppressWarnings("deprecation")
ServiceAccountCredentials credentials = new ServiceAccountCredentials(
null, "[email protected]", pair.getPrivate(), null, null) {
@Override
public AccessToken refreshAccessToken() {
throw new AssertionError();
}
};
GoogleAuthLibraryCallCredentials callCredentials =
new GoogleAuthLibraryCallCredentials(credentials);
callCredentials.applyRequestMetadata(method, attrs, executor, applier);
assertEquals(0, runPendingRunnables());
verify(applier).apply(headersCaptor.capture());
Metadata headers = headersCaptor.getValue();
String[] authorization = Iterables.toArray(headers.getAll(AUTHORIZATION), String.class);
assertEquals(1, authorization.length);
assertTrue(authorization[0], authorization[0].startsWith("Bearer "));
// JWT is reasonably long. Normal tokens aren't.
assertTrue(authorization[0], authorization[0].length() > 300);
}
示例11: serviceAccountWithScopeNotToJwt
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
@Test
public void serviceAccountWithScopeNotToJwt() throws Exception {
final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
@SuppressWarnings("deprecation")
ServiceAccountCredentials credentials = new ServiceAccountCredentials(
null, "[email protected]", pair.getPrivate(), null, Arrays.asList("somescope")) {
@Override
public AccessToken refreshAccessToken() {
return token;
}
};
GoogleAuthLibraryCallCredentials callCredentials =
new GoogleAuthLibraryCallCredentials(credentials);
callCredentials.applyRequestMetadata(method, attrs, executor, applier);
assertEquals(1, runPendingRunnables());
verify(applier).apply(headersCaptor.capture());
Metadata headers = headersCaptor.getValue();
Iterable<String> authorization = headers.getAll(AUTHORIZATION);
assertArrayEquals(new String[]{"Bearer allyourbase"},
Iterables.toArray(authorization, String.class));
}
示例12: onChanged
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
@Override
public final synchronized void onChanged(OAuth2Credentials credentials) throws IOException {
if (state.get() != State.STARTED) {
return;
}
AccessToken accessToken = credentials.getAccessToken();
long refreshDelay = getRefreshDelay(accessToken);
if (refreshDelay > 0) {
scheduleRefresh(refreshDelay);
} else {
logger.warn("Token expiry ({}) is less than 5 minutes in the future. Not "
+ "scheduling a proactive refresh.", accessToken.getExpirationTime());
}
}
示例13: wrapOAuthToken
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
private static String wrapOAuthToken(AccessToken result, Map<String, Object> authVariable) {
if (result == null) {
// This shouldn't happen in the actual production SDK, but can happen in tests.
return null;
}
GAuthToken googleAuthToken = new GAuthToken(result.getTokenValue(), authVariable);
return googleAuthToken.serializeToString();
}
示例14: getAccessToken
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
@Override
public Task<GoogleOAuthAccessToken> getAccessToken() {
try {
AccessToken accessToken = googleCredentials.refreshAccessToken();
GoogleOAuthAccessToken googleToken = new GoogleOAuthAccessToken(accessToken.getTokenValue(),
accessToken.getExpirationTime().getTime());
return Tasks.forResult(googleToken);
} catch (Exception e) {
return Tasks.forException(e);
}
}
示例15: refreshAccessToken
import com.google.auth.oauth2.AccessToken; //导入依赖的package包/类
@Override
public AccessToken refreshAccessToken() throws IOException {
try {
GoogleOAuthAccessToken token = Tasks.await(credential.getAccessToken());
return new AccessToken(token.getAccessToken(), new Date(token.getExpiryTime()));
} catch (ExecutionException | InterruptedException e) {
throw new IOException("Error while obtaining OAuth2 token", e);
}
}