Class OAuth2Credentials
- java.lang.Object
-
- com.google.auth.Credentials
-
- com.google.auth.oauth2.OAuth2Credentials
-
- All Implemented Interfaces:
java.io.Serializable
- Direct Known Subclasses:
DownscopedCredentials
,GoogleCredentials
,IdTokenCredentials
,OAuth2CredentialsWithRefresh
public class OAuth2Credentials extends Credentials
Base type for Credentials using OAuth2.- See Also:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description (package private) static class
OAuth2Credentials.AsyncRefreshResult
Result fromgetOrCreateRefreshTask()
.static class
OAuth2Credentials.Builder
(package private) static class
OAuth2Credentials.CacheState
static interface
OAuth2Credentials.CredentialsChangedListener
Listener for changes to credentials.(package private) static class
OAuth2Credentials.FutureCallbackToMetadataCallbackAdapter
(package private) static class
OAuth2Credentials.OAuthValue
Stores an immutable snapshot of the accesstoken owned byOAuth2Credentials
(package private) class
OAuth2Credentials.RefreshTask
(package private) class
OAuth2Credentials.RefreshTaskListener
-
Field Summary
Fields Modifier and Type Field Description private java.util.List<OAuth2Credentials.CredentialsChangedListener>
changeListeners
(package private) com.google.api.client.util.Clock
clock
(package private) static java.time.Duration
DEFAULT_EXPIRATION_MARGIN
(package private) static java.time.Duration
DEFAULT_REFRESH_MARGIN
private static com.google.common.collect.ImmutableMap<java.lang.String,java.util.List<java.lang.String>>
EMPTY_EXTRA_HEADERS
private java.time.Duration
expirationMargin
(package private) java.lang.Object
lock
private java.time.Duration
refreshMargin
(package private) OAuth2Credentials.RefreshTask
refreshTask
private static long
serialVersionUID
private OAuth2Credentials.OAuthValue
value
-
Fields inherited from class com.google.auth.Credentials
GOOGLE_DEFAULT_UNIVERSE
-
-
Constructor Summary
Constructors Modifier Constructor Description protected
OAuth2Credentials()
Default constructor.protected
OAuth2Credentials(AccessToken accessToken)
Constructor with explicit access token.protected
OAuth2Credentials(AccessToken accessToken, java.time.Duration refreshMargin, java.time.Duration expirationMargin)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description void
addChangeListener(OAuth2Credentials.CredentialsChangedListener listener)
Adds a listener that is notified when the Credentials data changes.private com.google.common.util.concurrent.ListenableFuture<OAuth2Credentials.OAuthValue>
asyncFetch(java.util.concurrent.Executor executor)
Attempts to get a fresh token.static OAuth2Credentials
create(AccessToken accessToken)
Returns the credentials instance from the given access token.boolean
equals(java.lang.Object obj)
private void
finishRefreshAsync(com.google.common.util.concurrent.ListenableFuture<OAuth2Credentials.OAuthValue> finishedTask)
Async callback for committing the result from a token refresh.AccessToken
getAccessToken()
Returns the cached access token.protected java.util.Map<java.lang.String,java.util.List<java.lang.String>>
getAdditionalHeaders()
Provide additional headers to return as request metadata.java.lang.String
getAuthenticationType()
A constant string name describing the authentication technology.(package private) java.time.Duration
getExpirationMargin()
Returns the credentials' expiration margin.protected static <T> T
getFromServiceLoader(java.lang.Class<? extends T> clazz, T defaultInstance)
private OAuth2Credentials.AsyncRefreshResult
getOrCreateRefreshTask()
Atomically creates a single flight refresh token task.(package private) java.time.Duration
getRefreshMargin()
Returns the credentials' refresh margin.java.util.Map<java.lang.String,java.util.List<java.lang.String>>
getRequestMetadata(java.net.URI uri)
Provide the request metadata by ensuring there is a current access token and providing it as an authorization bearer token.void
getRequestMetadata(java.net.URI uri, java.util.concurrent.Executor executor, RequestMetadataCallback callback)
Get the current request metadata without blocking.protected java.util.Map<java.lang.String,java.util.List<java.lang.String>>
getRequestMetadataInternal()
private OAuth2Credentials.CacheState
getState()
Computes the effective credential state in relation to the current time.int
hashCode()
boolean
hasRequestMetadata()
Whether the credentials have metadata entries that should be added to each request.boolean
hasRequestMetadataOnly()
Indicates whether or not the Auth mechanism works purely by including request metadata.static OAuth2Credentials.Builder
newBuilder()
protected static <T> T
newInstance(java.lang.String className)
private void
readObject(java.io.ObjectInputStream input)
void
refresh()
Request a new token regardless of the current token state.AccessToken
refreshAccessToken()
Method to refresh the access token according to the specific type of credentials.void
refreshIfExpired()
Refresh these credentials only if they have expired or are expiring imminently.void
removeChangeListener(OAuth2Credentials.CredentialsChangedListener listener)
Removes a listener that was added previously.OAuth2Credentials.Builder
toBuilder()
java.lang.String
toString()
private static <T> T
unwrapDirectFuture(com.google.common.util.concurrent.ListenableFuture<T> future)
Unwraps the value from the future.-
Methods inherited from class com.google.auth.Credentials
blockingGetToCallback, getMetricsCredentialType, getRequestMetadata, getUniverseDomain
-
-
-
-
Field Detail
-
serialVersionUID
private static final long serialVersionUID
- See Also:
- Constant Field Values
-
DEFAULT_EXPIRATION_MARGIN
static final java.time.Duration DEFAULT_EXPIRATION_MARGIN
-
DEFAULT_REFRESH_MARGIN
static final java.time.Duration DEFAULT_REFRESH_MARGIN
-
EMPTY_EXTRA_HEADERS
private static final com.google.common.collect.ImmutableMap<java.lang.String,java.util.List<java.lang.String>> EMPTY_EXTRA_HEADERS
-
expirationMargin
private final java.time.Duration expirationMargin
-
refreshMargin
private final java.time.Duration refreshMargin
-
lock
final java.lang.Object lock
-
value
private volatile OAuth2Credentials.OAuthValue value
-
refreshTask
transient OAuth2Credentials.RefreshTask refreshTask
-
changeListeners
private transient java.util.List<OAuth2Credentials.CredentialsChangedListener> changeListeners
-
clock
transient com.google.api.client.util.Clock clock
-
-
Constructor Detail
-
OAuth2Credentials
protected OAuth2Credentials()
Default constructor.
-
OAuth2Credentials
protected OAuth2Credentials(AccessToken accessToken)
Constructor with explicit access token.- Parameters:
accessToken
- initial or temporary access token
-
OAuth2Credentials
protected OAuth2Credentials(AccessToken accessToken, java.time.Duration refreshMargin, java.time.Duration expirationMargin)
-
-
Method Detail
-
create
public static OAuth2Credentials create(AccessToken accessToken)
Returns the credentials instance from the given access token.- Parameters:
accessToken
- the access token- Returns:
- the credentials instance
-
getAuthenticationType
public java.lang.String getAuthenticationType()
Description copied from class:Credentials
A constant string name describing the authentication technology.E.g. “OAuth2”, “SSL”. For use by the transport layer to determine whether it supports the type of authentication in the case where
Credentials.hasRequestMetadataOnly()
is false. Also serves as a debugging helper.- Specified by:
getAuthenticationType
in classCredentials
- Returns:
- The type of authentication used.
-
hasRequestMetadata
public boolean hasRequestMetadata()
Description copied from class:Credentials
Whether the credentials have metadata entries that should be added to each request.This should be called by the transport layer to see if
Credentials.getRequestMetadata()
should be used for each request.- Specified by:
hasRequestMetadata
in classCredentials
- Returns:
- Whether or not the transport layer should call
Credentials.getRequestMetadata()
-
hasRequestMetadataOnly
public boolean hasRequestMetadataOnly()
Description copied from class:Credentials
Indicates whether or not the Auth mechanism works purely by including request metadata.This is meant for the transport layer. If this is true a transport does not need to take actions other than including the request metadata. If this is false, a transport must specifically know about the authentication technology to support it, and should fail to accept the credentials otherwise.
- Specified by:
hasRequestMetadataOnly
in classCredentials
- Returns:
- Whether or not the Auth mechanism works purely by including request metadata.
-
getAccessToken
public final AccessToken getAccessToken()
Returns the cached access token.If not set, you should call
refresh()
to fetch and cache an access token.- Returns:
- The cached access token.
-
getRefreshMargin
java.time.Duration getRefreshMargin()
Returns the credentials' refresh margin.
-
getExpirationMargin
java.time.Duration getExpirationMargin()
Returns the credentials' expiration margin.
-
getRequestMetadata
public void getRequestMetadata(java.net.URI uri, java.util.concurrent.Executor executor, RequestMetadataCallback callback)
Description copied from class:Credentials
Get the current request metadata without blocking.This should be called by the transport layer on each request, and the data should be populated in headers or other context. The implementation can either call the callback inline or asynchronously. Either way it should never block in this method. The executor is provided for tasks that may block.
The default implementation will just call
Credentials.getRequestMetadata(URI)
then the callback from the given executor.The convention for handling binary data is for the key in the returned map to end with
"-bin"
and for the corresponding values to be base64 encoded.- Overrides:
getRequestMetadata
in classCredentials
- Parameters:
uri
- URI of the entry point for the request.executor
- Executor to perform the request.callback
- Callback to execute when the request is finished.
-
getRequestMetadata
public java.util.Map<java.lang.String,java.util.List<java.lang.String>> getRequestMetadata(java.net.URI uri) throws java.io.IOException
Provide the request metadata by ensuring there is a current access token and providing it as an authorization bearer token.- Specified by:
getRequestMetadata
in classCredentials
- Parameters:
uri
- URI of the entry point for the request.- Returns:
- The request metadata used for populating headers or other context.
- Throws:
java.io.IOException
- if there was an error getting up-to-date access. The exception should implementRetryable
andisRetryable()
will return true if the operation may be retried.
-
refresh
public void refresh() throws java.io.IOException
Request a new token regardless of the current token state. If the current token is not expired, it will still be returned during the refresh.- Specified by:
refresh
in classCredentials
- Throws:
java.io.IOException
- if there was an error getting up-to-date access.
-
refreshIfExpired
public void refreshIfExpired() throws java.io.IOException
Refresh these credentials only if they have expired or are expiring imminently.- Throws:
java.io.IOException
- during token refresh.
-
asyncFetch
private com.google.common.util.concurrent.ListenableFuture<OAuth2Credentials.OAuthValue> asyncFetch(java.util.concurrent.Executor executor)
Attempts to get a fresh token.If a fresh token is already available, it will be immediately returned. Otherwise a refresh will be scheduled using the passed in executor. While a token is being freshed, a stale value will be returned.
-
getOrCreateRefreshTask
private OAuth2Credentials.AsyncRefreshResult getOrCreateRefreshTask()
Atomically creates a single flight refresh token task.Only a single refresh task can be scheduled at a time. If there is an existing task, it will be returned for subsequent invocations. However if a new task is created, it is the responsibility of the caller to execute it. The task will clear the single flight slow upon completion.
-
finishRefreshAsync
private void finishRefreshAsync(com.google.common.util.concurrent.ListenableFuture<OAuth2Credentials.OAuthValue> finishedTask)
Async callback for committing the result from a token refresh.The result will be stored, listeners are invoked and the single flight slot is cleared.
-
unwrapDirectFuture
private static <T> T unwrapDirectFuture(com.google.common.util.concurrent.ListenableFuture<T> future) throws java.io.IOException
Unwraps the value from the future.Under most circumstances, the underlying future will already be resolved by the DirectExecutor. In those cases, the error stacktraces will be rooted in the caller's call tree. However, in some cases when async and sync usage is mixed, it's possible that a blocking call will await an async future. In those cases, the stacktrace will be orphaned and be rooted in a thread of whatever executor the async call used. This doesn't affect correctness and is extremely unlikely.
- Throws:
java.io.IOException
-
getState
private OAuth2Credentials.CacheState getState()
Computes the effective credential state in relation to the current time.
-
refreshAccessToken
public AccessToken refreshAccessToken() throws java.io.IOException
Method to refresh the access token according to the specific type of credentials.Throws IllegalStateException if not overridden since direct use of OAuth2Credentials is only for temporary or non-refreshing access tokens.
- Returns:
- never
- Throws:
java.lang.IllegalStateException
- always. OAuth2Credentials does not support refreshing the access token. An instance with a new access token or a derived type that supports refreshing should be used instead.java.io.IOException
-
getAdditionalHeaders
protected java.util.Map<java.lang.String,java.util.List<java.lang.String>> getAdditionalHeaders()
Provide additional headers to return as request metadata.- Returns:
- additional headers
-
addChangeListener
public final void addChangeListener(OAuth2Credentials.CredentialsChangedListener listener)
Adds a listener that is notified when the Credentials data changes.This is called when token content changes, such as when the access token is refreshed. This is typically used by code caching the access token.
- Parameters:
listener
- the listener to be added
-
removeChangeListener
public final void removeChangeListener(OAuth2Credentials.CredentialsChangedListener listener)
Removes a listener that was added previously.- Parameters:
listener
- The listener to be removed.
-
hashCode
public int hashCode()
- Overrides:
hashCode
in classjava.lang.Object
-
getRequestMetadataInternal
@Nullable protected java.util.Map<java.lang.String,java.util.List<java.lang.String>> getRequestMetadataInternal()
-
toString
public java.lang.String toString()
- Overrides:
toString
in classjava.lang.Object
-
equals
public boolean equals(java.lang.Object obj)
- Overrides:
equals
in classjava.lang.Object
-
readObject
private void readObject(java.io.ObjectInputStream input) throws java.io.IOException, java.lang.ClassNotFoundException
- Throws:
java.io.IOException
java.lang.ClassNotFoundException
-
newInstance
protected static <T> T newInstance(java.lang.String className) throws java.io.IOException, java.lang.ClassNotFoundException
- Throws:
java.io.IOException
java.lang.ClassNotFoundException
-
getFromServiceLoader
protected static <T> T getFromServiceLoader(java.lang.Class<? extends T> clazz, T defaultInstance)
-
newBuilder
public static OAuth2Credentials.Builder newBuilder()
-
toBuilder
public OAuth2Credentials.Builder toBuilder()
-
-