com.google.api.client.googleapis.auth.oauth.package.html Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of google-api-client Show documentation
Show all versions of google-api-client Show documentation
Google API Client Library for Java. Supports Java 5 (or higher) desktop (SE)
and web (EE), Android, and Google App Engine.
Google's additions to OAuth 1.0a authorization as specified in
Google's
OAuth API Reference
(see detailed package specification).
Package Specification
Before using this library, you need to set up your application as
follows:
- For a web application, you should first register your application at
the registration
page. You will be provided with two pieces of information you will need:
- OAuth Consumer Key: use this as the {@code consumerKey} on every
OAuth request, for example in {@link
com.google.api.client.auth.oauth.AbstractOAuthGetToken#consumerKey}.
- OAuth Consumer Secret: use this as the {@link
com.google.api.client.auth.oauth.OAuthHmacSigner#clientSharedSecret} when
using the {@code "HMAC-SHA1"} signature method.
- For an installed application, an unregistered web application, or a
web application running on localhost, you must use the {@code "HMAC-SHA1"}
signature method. Use {@code "anonymous"} for the {@code consumerKey} and
{@code clientSharedSecret}.
- For the {@code "HMAC-SHA1"} signature method, use {@link
com.google.api.client.auth.oauth.OAuthHmacSigner}.
- For the {@code "RSA-SHA1"} signature method, use {@link
com.google.api.client.auth.oauth.OAuthRsaSigner}. See the instructions for generating
a self-signing private key and public certificate .
After the set up has been completed, the typical application flow is:
- Request a temporary credentials token ("request token") from the
Google Authorization server using {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken}. A
callback URL should be specified for web applications, but does not need to be
specified for installed applications.
- Direct the end user to a Google Accounts web page to allow the end
user to authorize the temporary token using using {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthAuthorizeTemporaryTokenUrl}.
- After the user has granted the authorization:
- For web applications, the user's browser will be redirected to the
callback URL which may be parsed using {@link
com.google.api.client.auth.oauth.OAuthCallbackUrl}.
- For installed applications, use {@code ""} for the verification
code.
- Request to exchange the temporary token for a long-lived access token
from the Google Authorization server using {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken}. This
access token must be stored.
- Use the stored access token to authorize HTTP requests to protected
resources in Google services by setting the {@link
com.google.api.client.auth.oauth.OAuthParameters#token} and invoking {@link
com.google.api.client.auth.oauth.OAuthParameters#signRequestsUsingAuthorizationHeader}.
- For 2-legged OAuth, use {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthDomainWideDelegation}
as a request execute intercepter to set the e-mail address of the user on
every HTTP request, or {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthDomainWideDelegation.Url}
as a generic URL builder with the requestor ID parameter.
- To revoke an access token, use {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken#revokeAccessToken}.
Users can also manually revoke tokens from Google's change
authorized websites page.
For example:
import com.google.api.client.auth.*;
import com.google.api.client.auth.oauth.*;
import com.google.api.client.googleapis.*;
import com.google.api.client.googleapis.auth.oauth.*;
import com.google.api.client.http.*;
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.*;
import javax.servlet.http.*;
public class PicasaSample extends HttpServlet {
private static final String CONSUMER_KEY = "...";
/**
* OAuth type. This is only needed for a general-purpose sample. In a real
* application, normally only one kind of auth is used.
*/
enum OAuthType {
REGISTERED_RSA, REGISTERED_HMAC, UNREGISTERED_HMAC
}
static final OAuthType OAUTH_TYPE = OAuthType.REGISTERED_RSA;
private static final String CONSUMER_KEY =
OAUTH_TYPE == OAuthType.UNREGISTERED_HMAC ? "anonymous" : "...";
/**
* In-memory access token store. But this is bad practice! For example, if the
* process dies, all tokens would be lost. Instead, the long-lived access
* token credentials should be stored in a long-lived location for example in
* a database.
*/
static Map<String , TokenInfo> OAUTH_TOKENS = new HashMap<String, TokenInfo>();
static final class TokenInfo {
final boolean temporary;
final String token;
final String tokenSecret;
TokenInfo(OAuthCredentialsResponse response) {
this.token = response.token;
this.tokenSecret = response.tokenSecret;
this.temporary = response.callbackConfirmed != null;
}
OAuthParameters createParameters() throws IOException {
OAuthParameters result = new OAuthParameters();
result.consumerKey = CONSUMER_KEY;
result.signer = createSigner(this);
result.token = token;
return result;
}
}
private static TokenInfo execute(AbstractOAuthGetToken request)
throws IOException {
OAuthCredentialsResponse response = request.execute();
TokenInfo result = new TokenInfo(response);
OAUTH_TOKENS.put(getCurrentUserId(), result);
return result;
}
private static final String SCOPE = "http://picasaweb.google.com/data";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
PrintWriter writer = response.getWriter();
GoogleTransport transport = new GoogleTransport();
transport.applicationName = "...";
transport.setVersionHeader(PicasaWebAlbums.VERSION);
try {
String thisURL = request.getRequestURI();
String userId = getCurrentUserId();
TokenInfo tokenInfo = OAUTH_TOKENS.get(userId);
StringBuffer fullUrlBuf = request.getRequestURL();
if (request.getQueryString() != null) {
fullUrlBuf.append('?').append(request.getQueryString());
}
String fullUrl = fullUrlBuf.toString();
OAuthCallbackUrl authorizeResponse = new OAuthCallbackUrl(fullUrl);
if (tokenInfo != null && tokenInfo.temporary
&& authorizeResponse.verifier == null) {
tokenInfo = null;
}
OAuthSigner signer = createSigner(tokenInfo);
if (tokenInfo == null) {
GoogleOAuthGetTemporaryToken requestToken =
new GoogleOAuthGetTemporaryToken();
requestToken.signer = signer;
requestToken.consumerKey = CONSUMER_KEY;
requestToken.scope = SCOPE;
requestToken.callback = request.getRequestURL().toString();
tokenInfo = execute(requestToken);
GoogleOAuthAuthorizeTemporaryTokenUrl authorizeUrl =
new GoogleOAuthAuthorizeTemporaryTokenUrl();
authorizeUrl.temporaryToken = tokenInfo.token;
response.sendRedirect(authorizeUrl.build());
return;
}
if (tokenInfo.temporary) {
GoogleOAuthGetAccessToken accessToken =
new GoogleOAuthGetAccessToken();
accessToken.temporaryToken = tokenInfo.token;
accessToken.signer = signer;
accessToken.consumerKey = CONSUMER_KEY;
accessToken.verifier = authorizeResponse.verifier;
tokenInfo = execute(accessToken);
signer = createSigner(tokenInfo);
}
tokenInfo.createParameters().signRequestsUsingAuthorizationHeader(
transport);
run(writer, transport);
} catch (Exception e) {
handleException(writer, e);
}
}
private static OAuthSigner createSigner(TokenInfo tokenInfo)
throws IOException {
if (OAUTH_TYPE == OAuthType.REGISTERED_RSA) {
OAuthRsaSigner result = new OAuthRsaSigner();
result.privateKey = getPrivateKey();
return result;
}
OAuthHmacSigner result = new OAuthHmacSigner();
result.clientSharedSecret =
OAUTH_TYPE == OAuthType.UNREGISTERED_HMAC ? "anonymous" : "...";
if (tokenInfo != null) {
result.tokenSharedSecret = tokenInfo.tokenSecret;
}
return result;
}
private static PrivateKey getPrivateKey() throws IOException {
if (privateKey == null) {
try {
privateKey =
RsaSha.getPrivateKeyFromKeystore(new FileInputStream(
"WEB-INF/....jks"), "...", "...", "...");
} catch (GeneralSecurityException e) {
throw new IOException(e);
}
}
return privateKey;
}
}
To later revoke the token:
for (Map.Entry<String, TokenInfo> entry : OAUTH_TOKENS.entrySet()) {
TokenInfo tokenInfo = entry.getValue();
if (!tokenInfo.temporary) {
String user = entry.getKey();
try {
OAuthParameters parameters = tokenInfo.createParameters();
GoogleOAuthGetAccessToken.revokeAccessToken(parameters);
} catch (Exception e) {
handleException(writer, e);
}
}
}
OAUTH_TOKENS.clear();
This package depends on the {@link com.google.api.client.auth.oauth},
{@link com.google.api.client.googleapis}, {@link com.google.api.client.http},
and {@link com.google.api.client.util} packages.
Warning: this package is experimental, and its content may be
changed in incompatible ways or possibly entirely removed in a future version of
the library
@since 1.0
© 2015 - 2024 Weber Informatics LLC | Privacy Policy