Google's additions to OAuth 2.0 authorization as specified in Using OAuth 2.0 to Access Google APIs.
Before using this library, you must register your application at the APIs Console. The result of this registration process is a set of values that are known to both Google and your application, such as the "Client ID", "Client Secret", and "Redirect URIs".
These are the typical steps of the web server flow based on an authorization code, as specified in Using OAuth 2.0 for Web Server Applications:
- Redirect the end user in the browser to the authorization page using com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl to grant your application access to the end user's protected data.
- Process the authorization response using com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl to parse the authorization code.
- Request an access token and possibly a refresh token using com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest.
- Access protected resources using com.google.api.client.googleapis.auth.oauth2.GoogleCredential. Expired access tokens will automatically be refreshed using the refresh token (if applicable).
These are the typical steps of the the browser-based client flow specified in Using OAuth 2.0 for Client-side Applications:
- Redirect the end user in the browser to the authorization page using com.google.api.client.googleapis.auth.oauth2.GoogleBrowserClientRequestUrl to grant your browser application access to the end user's protected data.
- Use the Google API Client library for JavaScript to process the access token found in the URL fragment at the redirect URI registered at the APIs Console.
Classes
CloudShellCredential (deprecated)
Deprecated. Please use google-auth-library for handling authentication and authorization from Cloud Shell.
OAuth2 credentials representing the built-in service account for Google Cloud Shell.
GoogleAuthorizationCodeFlow
Thread-safe Google OAuth 2.0 authorization code flow that manages and persists end-user credentials.
This is designed to simplify the flow in which an end-user authorizes the application to access their protected data, and then the application has access to their data based on an access token and a refresh token to refresh that access token when it expires.
The first step is to call #loadCredential(String) based on the known user ID to check
if the end-user's credentials are already known. If not, call #newAuthorizationUrl() and
direct the end-user's browser to an authorization page. The web browser will then redirect to the
redirect URL with a "code"
query parameter which can then be used to request an access
token using #newTokenRequest(String). Finally, use #createAndStoreCredential(TokenResponse, String) to store and obtain a credential for accessing
protected resources.
The default for the approval_prompt
and access_type
parameters is
null
. For web applications that means "approval_prompt=auto&access_type=online"
and for
installed applications that means "approval_prompt=force&access_type=offline"
. To
override the default, you need to explicitly call Builder#setApprovalPrompt(String) and
Builder#setAccessType(String).
GoogleAuthorizationCodeFlow.Builder
Google authorization code flow builder.
Implementation is not thread-safe.
GoogleAuthorizationCodeRequestUrl
Google-specific implementation of the OAuth 2.0 URL builder for an authorization web page to allow the end user to authorize the application to access their protected resources and that returns an authorization code, as specified in Using OAuth 2.0 for Web Server Applications.
The default for #getResponseTypes() is "code"
. Use AuthorizationCodeResponseUrl to parse the redirect response after the end user grants/denies the
request. Using the authorization code in this response, use GoogleAuthorizationCodeTokenRequest to request the access token.
Sample usage for a web application:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String url = new GoogleAuthorizationCodeRequestUrl(
"812741506391.apps.googleusercontent.com",
"https://oauth2-login-demo.appspot.com/code",
Arrays.asList("https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile"))
.setState("/profile").build();
response.sendRedirect(url);
}
Implementation is not thread-safe.
GoogleAuthorizationCodeTokenRequest
Google-specific implementation of the OAuth 2.0 request for an access token based on an authorization code (as specified in Using OAuth 2.0 for Web Server Applications).
Use GoogleCredential to access protected resources from the resource server using the TokenResponse returned by #execute(). On error, it will instead throw TokenResponseException.
Sample usage:
static void requestAccessToken() throws IOException {
try {
GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(), new GsonFactory(),
"812741506391.apps.googleusercontent.com", "{client_secret}",
"4/P7q7W91a-oMsCeLvIaQm6bTrgtp7", "https://oauth2-login-demo.appspot.com/code")
.execute();
System.out.println("Access token: " + response.getAccessToken());
} catch (TokenResponseException e) {
if (e.getDetails() != null) {
System.err.println("Error: " + e.getDetails().getError());
if (e.getDetails().getErrorDescription() != null) {
System.err.println(e.getDetails().getErrorDescription());
}
if (e.getDetails().getErrorUri() != null) {
System.err.println(e.getDetails().getErrorUri());
}
} else {
System.err.println(e.getMessage());
}
}
}
Implementation is not thread-safe.
GoogleBrowserClientRequestUrl
Google-specific implementation of the OAuth 2.0 URL builder for an authorization web page to allow the end user to authorize the application to access their protected resources and that returns the access token to a browser client using a scripting language such as JavaScript, as specified in Using OAuth 2.0 for Client-side Applications.
The default for #getResponseTypes() is "token"
.
Sample usage for a web application:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String url = new GoogleBrowserClientRequestUrl("812741506391.apps.googleusercontent.com",
"https://oauth2-login-demo.appspot.com/oauthcallback", Arrays.asList(
"https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"))
.setState("/profile").build();
response.sendRedirect(url);
}
Implementation is not thread-safe.
GoogleClientSecrets
OAuth 2.0 client secrets JSON model as specified in client_secrets.json file format.
Sample usage:
static GoogleClientSecrets loadClientSecretsResource(JsonFactory jsonFactory)
throws IOException {
return GoogleClientSecrets.load(
jsonFactory,
new InputStreamReader(
SampleClass.class.getResourceAsStream("/client_secrets.json"), "UTF-8"
)
);
}
GoogleClientSecrets.Details
Client credential details.
GoogleCredential (deprecated)
Deprecated. Please use google-auth-library for handling Application Default Credentials and other non-OAuth2 based authentication.
Thread-safe Google-specific implementation of the OAuth 2.0 helper for accessing protected resources using an access token, as well as optionally refreshing the access token when it expires using a refresh token.
There are three modes supported: access token only, refresh token flow, and service account flow (with or without impersonating a user).
If all you have is an access token, you simply pass the TokenResponse to the credential using Builder#setFromTokenResponse(TokenResponse). Google credential uses BearerToken#authorizationHeaderAccessMethod() as the access method. Sample usage:
public static GoogleCredential createCredentialWithAccessTokenOnly(TokenResponse tokenResponse) {
return new GoogleCredential().setFromTokenResponse(tokenResponse);
}
If you have a refresh token, it is similar to the case of access token only, but you additionally need to pass the credential the client secrets using Builder#setClientSecrets(GoogleClientSecrets) or Builder#setClientSecrets(String, String). Google credential uses GoogleOAuthConstants#TOKEN_SERVER_URL as the token server URL, and ClientParametersAuthentication with the client ID and secret as the client authentication. Sample usage:
public static GoogleCredential createCredentialWithRefreshToken(
HttpTransport transport, JsonFactory jsonFactory,
GoogleClientSecrets clientSecrets, TokenResponse tokenResponse) {
return new GoogleCredential.Builder().setTransport(transport)
.setJsonFactory(jsonFactory)
.setClientSecrets(clientSecrets)
.build()
.setFromTokenResponse(tokenResponse);
}
The service
account flow is used when you want to access data owned by your client application. You
download the private key in a .p12
file from the Google APIs Console. Use Builder#setServiceAccountId(String), Builder#setServiceAccountPrivateKeyFromP12File(File), and Builder#setServiceAccountScopes(Collection). Sample usage:
public static GoogleCredential createCredentialForServiceAccount(HttpTransport transport,
JsonFactory jsonFactory,
String serviceAccountId, Collection<String> serviceAccountScopes, File p12File)
throws GeneralSecurityException, IOException {
return new GoogleCredential.Builder().setTransport(transport).setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountId).setServiceAccountScopes(serviceAccountScopes)
.setServiceAccountPrivateKeyFromP12File(p12File).build();
}
You can also use the service account flow to impersonate a user in a domain that you own. This is very similar to the service account flow above, but you additionally call Builder#setServiceAccountUser(String). Sample usage:
public static GoogleCredential createCredentialForServiceAccountImpersonateUser
(HttpTransport transport, JsonFactory jsonFactory, String serviceAccountId,
Collection<String> serviceAccountScopes, File p12File,
String serviceAccountUser) throws GeneralSecurityException, IOException {
return new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountId)
.setServiceAccountScopes(serviceAccountScopes)
.setServiceAccountPrivateKeyFromP12File(p12File)
.setServiceAccountUser(serviceAccountUser)
.build();
}
If you need to persist the access token in a data store, use DataStoreFactory and Builder#addRefreshListener(CredentialRefreshListener) with DataStoreCredentialRefreshListener.
If you have a custom request initializer, request execute interceptor, or unsuccessful response handler, take a look at the sample usage for HttpExecuteInterceptor and HttpUnsuccessfulResponseHandler, which are interfaces that this class also implements.
GoogleCredential.Builder
Google credential builder.
Implementation is not thread-safe.
GoogleIdToken
Beta
Google ID tokens as specified in OpenID Connect.
Google ID tokens contain useful information about the authorized end user. Google ID tokens are signed and the signature must be verified using #verify(GoogleIdTokenVerifier).
Implementation is not thread-safe.
GoogleIdToken.Payload
Beta
Google ID token payload.
GoogleIdTokenVerifier
Beta
Thread-safe Google ID token verifier.
Call #verify(IdToken) to verify a ID token. Use the constructor #GoogleIdTokenVerifier(HttpTransport, JsonFactory) for the typical simpler case if your application has only a single instance of GoogleIdTokenVerifier. Otherwise, ideally you should use #GoogleIdTokenVerifier(GooglePublicKeysManager) with a shared global instance of the GooglePublicKeysManager since that way the Google public keys are cached. Sample usage:
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
.setAudience(Arrays.asList("myClientId"))
.build();
...
if (!verifier.verify(googleIdToken)) {...}
GoogleIdTokenVerifier.Builder
Beta
Builder for GoogleIdTokenVerifier.
Implementation is not thread-safe.
GoogleOAuthConstants
Constants for Google's OAuth 2.0 implementation.
GooglePublicKeysManager
Beta
Thread-safe Google public keys manager.
The public keys are loaded from the public certificates endpoint at #getPublicCertsEncodedUrl and cached in this instance. Therefore, for maximum efficiency, applications should use a single globally-shared instance of the GooglePublicKeysManager.
GooglePublicKeysManager.Builder
Beta
Builder for GooglePublicKeysManager.
Implementation is not thread-safe.
GoogleRefreshTokenRequest
Google-specific implementation of the OAuth 2.0 request to refresh an access token using a refresh token as specified in Refreshing an Access Token.
Use GoogleCredential to access protected resources from the resource server using the TokenResponse returned by #execute(). On error, it will instead throw TokenResponseException.
Sample usage:
static void refreshAccessToken() throws IOException {
try {
TokenResponse response = new GoogleRefreshTokenRequest(
new NetHttpTransport(), new GsonFactory(),
"tGzv3JOkF0XG5Qx2TlKWIA", "s6BhdRkqt3",
"7Fjfp0ZBr1KtDRbnfVdmIw").execute();
System.out.println("Access token: " + response.getAccessToken());
} catch (TokenResponseException e) {
if (e.getDetails() != null) {
System.err.println("Error: " + e.getDetails().getError());
if (e.getDetails().getErrorDescription() != null) {
System.err.println(e.getDetails().getErrorDescription());
}
if (e.getDetails().getErrorUri() != null) {
System.err.println(e.getDetails().getErrorUri());
}
} else {
System.err.println(e.getMessage());
}
}
}
Implementation is not thread-safe.
GoogleTokenResponse
Google OAuth 2.0 JSON model for a successful access token response as specified in Successful Response, including an ID token as specified in OpenID Connect Session Management 1.0.
This response object is the result of GoogleAuthorizationCodeTokenRequest#execute() and GoogleRefreshTokenRequest#execute(). Use #parseIdToken() to parse the GoogleIdToken and then call GoogleIdTokenVerifier#verify(GoogleIdToken).
Implementation is not thread-safe.
OAuth2Utils
Utilities used by the com.google.api.client.googleapis.auth.oauth2 namespace.