Implementing Server-Side Authorization - Drive REST API - Google Developers
Implementing Server-Side Authorization - Drive REST API - Google Developers
1 of 10
https://developers.google.com/drive/web/auth/web-server
Drive REX
5/10/2015 7:21 PM
2 of 10
https://developers.google.com/drive/web/auth/web-server
offline
approval_prompt
force
offline
CLIENTSECRET_LOCATION
client_secret.json
import com.google.api.client.auth.oauth2.Credential;
5/10/2015 7:21 PM
3 of 10
https://developers.google.com/drive/web/auth/web-server
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.oauth2.Oauth2;
import com.google.api.services.oauth2.model.Userinfoplus;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
// ...
class MyClass {
// Path to client_secret.json which should contain a JSON document such as:
//
{
//
//
"web": {
"client_id": "[[YOUR_CLIENT_ID]]",
//
//
"client_secret": "[[YOUR_CLIENT_SECRET]]",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
//
//
//
"token_uri": "https://accounts.google.com/o/oauth2/token"
}
}
5/10/2015 7:21 PM
4 of 10
https://developers.google.com/drive/web/auth/web-server
/**
* Set the authorization URL.
*/
public void setAuthorizationUrl(String authorizationUrl) {
this.authorizationUrl = authorizationUrl;
}
/**
* @return the authorizationUrl
*/
public String getAuthorizationUrl() {
return authorizationUrl;
}
}
/**
* Exception thrown when a code exchange has failed.
*/
public static class CodeExchangeException extends GetCredentialsException {
/**
* Construct a CodeExchangeException.
*
* @param authorizationUrl The authorization URL to redirect the user to.
*/
public CodeExchangeException(String authorizationUrl) {
super(authorizationUrl);
}
}
/**
* Exception thrown when no refresh token has been found.
*/
public static class NoRefreshTokenException extends GetCredentialsException {
/**
* Construct a NoRefreshTokenException.
*
* @param authorizationUrl The authorization URL to redirect the user to.
*/
public NoRefreshTokenException(String authorizationUrl) {
super(authorizationUrl);
}
}
/**
* Exception thrown when no user ID could be retrieved.
*/
private static class NoUserIdException extends Exception {
}
/**
* Retrieved stored credentials for the provided user ID.
*
* @param userId User's ID.
* @return Stored Credential if found, {@code null} otherwise.
*/
static Credential getStoredCredentials(String userId) {
5/10/2015 7:21 PM
5 of 10
https://developers.google.com/drive/web/auth/web-server
// TODO: Implement this method to work with your database. Instantiate a new
// Credential instance with stored accessToken and refreshToken.
throw new UnsupportedOperationException();
}
/**
* Store OAuth 2.0 credentials in the application's database.
*
* @param userId User's ID.
* @param credentials The OAuth 2.0 credentials to store.
*/
static void storeCredentials(String userId, Credential credentials) {
// TODO: Implement this method to work with your database.
// Store the credentials.getAccessToken() and credentials.getRefreshToken()
// string values in your database.
throw new UnsupportedOperationException();
}
/**
* Build an authorization flow and store it as a static class attribute.
*
* @return GoogleAuthorizationCodeFlow instance.
* @throws IOException Unable to load client_secret.json.
*/
static GoogleAuthorizationCodeFlow getFlow() throws IOException {
if (flow == null) {
InputStream in =
MyClass.class.getResourceAsStream(CLIENTSECRET_LOCATION);
GoogleClientSecrets clientSecret =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecret, SCOPES)
.setAccessType("offline")
.setApprovalPrompt("force")
.build();
}
return flow;
}
/**
* Exchange an authorization code for OAuth 2.0 credentials.
*
* @param authorizationCode Authorization code to exchange for OAuth 2.0
*
credentials.
* @return OAuth 2.0 credentials.
* @throws CodeExchangeException An error occurred.
*/
static Credential exchangeCode(String authorizationCode)
throws CodeExchangeException {
try {
GoogleAuthorizationCodeFlow flow = getFlow();
GoogleTokenResponse response = flow
.newTokenRequest(authorizationCode)
.setRedirectUri(REDIRECT_URI)
.execute();
return flow.createAndStoreCredential(response, null);
} catch (IOException e) {
5/10/2015 7:21 PM
6 of 10
https://developers.google.com/drive/web/auth/web-server
5/10/2015 7:21 PM
7 of 10
https://developers.google.com/drive/web/auth/web-server
5/10/2015 7:21 PM
8 of 10
https://developers.google.com/drive/web/auth/web-server
File
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.drive.Drive;
// ...
public class MyClass {
private static final String APPLICATION_NAME = "Your app name";
private static final JacksonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
private static final HttpTransport HTTP_TRANSPORT =
new NetHttpTransport();
// ...
/**
* Build a Drive service object.
*
* @param credentials OAuth 2.0 credentials.
* @return Drive service object.
*/
static Drive buildService(Credential credentials) {
return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials)
.setApplicationName(APPLICATION_NAME)
.build();
}
// ...
}
5/10/2015 7:21 PM
9 of 10
https://developers.google.com/drive/web/auth/web-server
GET
File
401
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import java.io.IOException;
// ...
public class MyClass {
// ...
/**
* Print a file's metadata.
*
* @param service Drive API service instance.
* @param fileId ID of the file to print metadata for.
*/
static void printFile(Drive service, String fileId) {
try {
File file = service.files().get(fileId).execute();
System.out.println("Title: " + file.getTitle());
System.out.println("Description: " + file.getDescription());
System.out.println("MIME type: " + file.getMimeType());
} catch (HttpResponseException e) {
if (e.getStatusCode() == 401) {
// Credentials have been revoked.
// TODO: Redirect the user to the authorization URL.
throw new UnsupportedOperationException();
}
} catch (IOException e) {
System.out.println("An error occurred: " + e);
}
}
// ...
}
5/10/2015 7:21 PM
10 of 10
https://developers.google.com/drive/web/auth/web-server
5/10/2015 7:21 PM