Implementing Server-Side Authorization - Drive REST API — Google Developers

Download Implementing Server-Side Authorization - Drive REST API — Google Developers

Post on 25-Sep-2015

7 views

Category:

Documents

4 download

Embed Size (px)

DESCRIPTION

Rest-API

TRANSCRIPT

<ul><li><p>XDrive RE</p><p>Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server</p><p>1 of 10 5/10/2015 7:21 PM</p></li><li><p>offline</p><p>approval_prompt force</p><p>offline</p><p>CLIENTSECRET_LOCATION client_secret.json</p><p>import com.google.api.client.auth.oauth2.Credential;</p><p>Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server</p><p>2 of 10 5/10/2015 7:21 PM</p></li><li><p>import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;</p><p>import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;</p><p>import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;</p><p>import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;</p><p>import com.google.api.client.http.HttpTransport;</p><p>import com.google.api.client.http.javanet.NetHttpTransport;</p><p>import com.google.api.client.json.jackson2.JacksonFactory;</p><p>import com.google.api.services.oauth2.Oauth2;</p><p>import com.google.api.services.oauth2.model.Userinfoplus;</p><p>import java.io.IOException;</p><p>import java.io.InputStream;</p><p>import java.io.InputStreamReader;</p><p>import java.util.Arrays;</p><p>import java.util.List;</p><p>// ...</p><p>class MyClass {</p><p> // Path to client_secret.json which should contain a JSON document such as:</p><p> // {</p><p> // "web": {</p><p> // "client_id": "[[YOUR_CLIENT_ID]]",</p><p> // "client_secret": "[[YOUR_CLIENT_SECRET]]",</p><p> // "auth_uri": "https://accounts.google.com/o/oauth2/auth",</p><p> // "token_uri": "https://accounts.google.com/o/oauth2/token"</p><p> // }</p><p> // }</p><p> private static final String CLIENTSECRET_LOCATION = "/client_secret.json";</p><p> private static final String APPLICATION_NAME = "Your app name";</p><p> private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";</p><p> private static final List SCOPES = Arrays.asList(</p><p> "https://www.googleapis.com/auth/drive.file",</p><p> "email",</p><p> "profile");</p><p> private static GoogleAuthorizationCodeFlow flow = null;</p><p> private static final JacksonFactory JSON_FACTORY =</p><p> JacksonFactory.getDefaultInstance();</p><p> private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();</p><p> /**</p><p> * Exception thrown when an error occurred while retrieving credentials.</p><p> */</p><p> public static class GetCredentialsException extends Exception {</p><p> protected String authorizationUrl;</p><p> /**</p><p> * Construct a GetCredentialsException.</p><p> *</p><p> * @param authorizationUrl The authorization URL to redirect the user to.</p><p> */</p><p> public GetCredentialsException(String authorizationUrl) {</p><p> this.authorizationUrl = authorizationUrl;</p><p> }</p><p>Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server</p><p>3 of 10 5/10/2015 7:21 PM</p></li><li><p> /**</p><p> * Set the authorization URL.</p><p> */</p><p> public void setAuthorizationUrl(String authorizationUrl) {</p><p> this.authorizationUrl = authorizationUrl;</p><p> }</p><p> /**</p><p> * @return the authorizationUrl</p><p> */</p><p> public String getAuthorizationUrl() {</p><p> return authorizationUrl;</p><p> }</p><p> }</p><p> /**</p><p> * Exception thrown when a code exchange has failed.</p><p> */</p><p> public static class CodeExchangeException extends GetCredentialsException {</p><p> /**</p><p> * Construct a CodeExchangeException.</p><p> *</p><p> * @param authorizationUrl The authorization URL to redirect the user to.</p><p> */</p><p> public CodeExchangeException(String authorizationUrl) {</p><p> super(authorizationUrl);</p><p> }</p><p> }</p><p> /**</p><p> * Exception thrown when no refresh token has been found.</p><p> */</p><p> public static class NoRefreshTokenException extends GetCredentialsException {</p><p> /**</p><p> * Construct a NoRefreshTokenException.</p><p> *</p><p> * @param authorizationUrl The authorization URL to redirect the user to.</p><p> */</p><p> public NoRefreshTokenException(String authorizationUrl) {</p><p> super(authorizationUrl);</p><p> }</p><p> }</p><p> /**</p><p> * Exception thrown when no user ID could be retrieved.</p><p> */</p><p> private static class NoUserIdException extends Exception {</p><p> }</p><p> /**</p><p> * Retrieved stored credentials for the provided user ID.</p><p> *</p><p> * @param userId User's ID.</p><p> * @return Stored Credential if found, {@code null} otherwise.</p><p> */</p><p> static Credential getStoredCredentials(String userId) {</p><p>Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server</p><p>4 of 10 5/10/2015 7:21 PM</p></li><li><p> // TODO: Implement this method to work with your database. Instantiate a new</p><p> // Credential instance with stored accessToken and refreshToken.</p><p> throw new UnsupportedOperationException();</p><p> }</p><p> /**</p><p> * Store OAuth 2.0 credentials in the application's database.</p><p> *</p><p> * @param userId User's ID.</p><p> * @param credentials The OAuth 2.0 credentials to store.</p><p> */</p><p> static void storeCredentials(String userId, Credential credentials) {</p><p> // TODO: Implement this method to work with your database.</p><p> // Store the credentials.getAccessToken() and credentials.getRefreshToken()</p><p> // string values in your database.</p><p> throw new UnsupportedOperationException();</p><p> }</p><p> /**</p><p> * Build an authorization flow and store it as a static class attribute.</p><p> *</p><p> * @return GoogleAuthorizationCodeFlow instance.</p><p> * @throws IOException Unable to load client_secret.json.</p><p> */</p><p> static GoogleAuthorizationCodeFlow getFlow() throws IOException {</p><p> if (flow == null) {</p><p> InputStream in =</p><p> MyClass.class.getResourceAsStream(CLIENTSECRET_LOCATION);</p><p> GoogleClientSecrets clientSecret =</p><p> GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));</p><p> flow = new GoogleAuthorizationCodeFlow.Builder(</p><p> HTTP_TRANSPORT, JSON_FACTORY, clientSecret, SCOPES)</p><p> .setAccessType("offline")</p><p> .setApprovalPrompt("force")</p><p> .build();</p><p> }</p><p> return flow;</p><p> }</p><p> /**</p><p> * Exchange an authorization code for OAuth 2.0 credentials.</p><p> *</p><p> * @param authorizationCode Authorization code to exchange for OAuth 2.0</p><p> * credentials.</p><p> * @return OAuth 2.0 credentials.</p><p> * @throws CodeExchangeException An error occurred.</p><p> */</p><p> static Credential exchangeCode(String authorizationCode)</p><p> throws CodeExchangeException {</p><p> try {</p><p> GoogleAuthorizationCodeFlow flow = getFlow();</p><p> GoogleTokenResponse response = flow</p><p> .newTokenRequest(authorizationCode)</p><p> .setRedirectUri(REDIRECT_URI)</p><p> .execute();</p><p> return flow.createAndStoreCredential(response, null);</p><p> } catch (IOException e) {</p><p>Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server</p><p>5 of 10 5/10/2015 7:21 PM</p></li><li><p> System.err.println("An error occurred: " + e);</p><p> throw new CodeExchangeException(null);</p><p> }</p><p> }</p><p> /**</p><p> * Send a request to the UserInfo API to retrieve the user's information.</p><p> *</p><p> * @param credentials OAuth 2.0 credentials to authorize the request.</p><p> * @return User's information.</p><p> * @throws NoUserIdException An error occurred.</p><p> */</p><p> static Userinfoplus getUserInfo(Credential credentials)</p><p> throws NoUserIdException {</p><p> Oauth2 userInfoService = new Oauth2.Builder(</p><p> HTTP_TRANSPORT, JSON_FACTORY, credentials)</p><p> .setApplicationName(APPLICATION_NAME)</p><p> .build();</p><p> Userinfoplus userInfo = null;</p><p> try {</p><p> userInfo = userInfoService.userinfo().get().execute();</p><p> } catch (IOException e) {</p><p> System.err.println("An error occurred: " + e);</p><p> }</p><p> if (userInfo != null &amp;&amp; userInfo.getId() != null) {</p><p> return userInfo;</p><p> } else {</p><p> throw new NoUserIdException();</p><p> }</p><p> }</p><p> /**</p><p> * Retrieve the authorization URL.</p><p> *</p><p> * @param emailAddress User's e-mail address.</p><p> * @param state State for the authorization URL.</p><p> * @return Authorization URL to redirect the user to.</p><p> * @throws IOException Unable to load client_secret.json.</p><p> */</p><p> public static String getAuthorizationUrl(String emailAddress, String state)</p><p> throws IOException {</p><p> GoogleAuthorizationCodeRequestUrl urlBuilder = getFlow()</p><p> .newAuthorizationUrl()</p><p> .setRedirectUri(REDIRECT_URI)</p><p> .setState(state);</p><p> urlBuilder.set("user_id", emailAddress);</p><p> return urlBuilder.build();</p><p> }</p><p> /**</p><p> * Retrieve credentials using the provided authorization code.</p><p> *</p><p> * This function exchanges the authorization code for an access token and</p><p> * queries the UserInfo API to retrieve the user's e-mail address. If a</p><p> * refresh token has been retrieved along with an access token, it is stored</p><p> * in the application database using the user's e-mail address as key. If no</p><p> * refresh token has been retrieved, the function checks in the application</p><p>Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server</p><p>6 of 10 5/10/2015 7:21 PM</p></li><li><p> * database for one and returns it if found or throws a NoRefreshTokenException</p><p> * with the authorization URL to redirect the user to.</p><p> *</p><p> * @param authorizationCode Authorization code to use to retrieve an access</p><p> * token.</p><p> * @param state State to set to the authorization URL in case of error.</p><p> * @return OAuth 2.0 credentials instance containing an access and refresh</p><p> * token.</p><p> * @throws NoRefreshTokenException No refresh token could be retrieved from</p><p> * the available sources.</p><p> * @throws IOException Unable to load client_secret.json.</p><p> */</p><p> public static Credential getCredentials(String authorizationCode, String state)</p><p> throws CodeExchangeException, NoRefreshTokenException, IOException {</p><p> String emailAddress = "";</p><p> try {</p><p> Credential credentials = exchangeCode(authorizationCode);</p><p> Userinfoplus userInfo = getUserInfo(credentials);</p><p> String userId = userInfo.getId();</p><p> emailAddress = userInfo.getEmail();</p><p> if (credentials.getRefreshToken() != null) {</p><p> storeCredentials(userId, credentials);</p><p> return credentials;</p><p> } else {</p><p> credentials = getStoredCredentials(userId);</p><p> if (credentials != null &amp;&amp; credentials.getRefreshToken() != null) {</p><p> return credentials;</p><p> }</p><p> }</p><p> } catch (CodeExchangeException e) {</p><p> e.printStackTrace();</p><p> // Drive apps should try to retrieve the user and credentials for the</p><p> // current session.</p><p> // If none is available, redirect the user to the authorization URL.</p><p> e.setAuthorizationUrl(getAuthorizationUrl(emailAddress, state));</p><p> throw e;</p><p> } catch (NoUserIdException e) {</p><p> e.printStackTrace();</p><p> }</p><p> // No refresh token has been retrieved.</p><p> String authorizationUrl = getAuthorizationUrl(emailAddress, state);</p><p> throw new NoRefreshTokenException(authorizationUrl);</p><p> }</p><p>}</p><p>Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server</p><p>7 of 10 5/10/2015 7:21 PM</p></li><li><p>File</p><p>import com.google.api.client.auth.oauth2.Credential;</p><p>import com.google.api.client.http.HttpTransport;</p><p>import com.google.api.client.http.javanet.NetHttpTransport;</p><p>import com.google.api.client.json.jackson2.JacksonFactory;</p><p>import com.google.api.services.drive.Drive;</p><p>// ...</p><p>public class MyClass {</p><p> private static final String APPLICATION_NAME = "Your app name";</p><p> private static final JacksonFactory JSON_FACTORY =</p><p> JacksonFactory.getDefaultInstance();</p><p> private static final HttpTransport HTTP_TRANSPORT =</p><p> new NetHttpTransport();</p><p> // ...</p><p> /**</p><p> * Build a Drive service object.</p><p> *</p><p> * @param credentials OAuth 2.0 credentials.</p><p> * @return Drive service object.</p><p> */</p><p> static Drive buildService(Credential credentials) {</p><p> return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials)</p><p> .setApplicationName(APPLICATION_NAME)</p><p> .build();</p><p> }</p><p> // ...</p><p>}</p><p>Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server</p><p>8 of 10 5/10/2015 7:21 PM</p></li><li><p>GET</p><p>File</p><p>401</p><p>import com.google.api.client.http.HttpResponse;</p><p>import com.google.api.client.http.HttpResponseException;</p><p>import com.google.api.services.drive.Drive;</p><p>import com.google.api.services.drive.model.File;</p><p>import java.io.IOException;</p><p>// ...</p><p>public class MyClass {</p><p> // ...</p><p> /**</p><p> * Print a file's metadata.</p><p> *</p><p> * @param service Drive API service instance.</p><p> * @param fileId ID of the file to print metadata for.</p><p> */</p><p> static void printFile(Drive service, String fileId) {</p><p> try {</p><p> File file = service.files().get(fileId).execute();</p><p> System.out.println("Title: " + file.getTitle());</p><p> System.out.println("Description: " + file.getDescription());</p><p> System.out.println("MIME type: " + file.getMimeType());</p><p> } catch (HttpResponseException e) {</p><p> if (e.getStatusCode() == 401) {</p><p> // Credentials have been revoked.</p><p> // TODO: Redirect the user to the authorization URL.</p><p> throw new UnsupportedOperationException();</p><p> }</p><p> } catch (IOException e) {</p><p> System.out.println("An error occurred: " + e);</p><p> }</p><p> }</p><p> // ...</p><p>}</p><p>Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server</p><p>9 of 10 5/10/2015 7:21 PM</p></li><li><p>Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server</p><p>10 of 10 5/10/2015 7:21 PM</p></li></ul>