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

  • XDrive RE

    Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server

    1 of 10 5/10/2015 7:21 PM

  • offline

    approval_prompt force

    offline

    CLIENTSECRET_LOCATION client_secret.json

    import com.google.api.client.auth.oauth2.Credential;

    Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server

    2 of 10 5/10/2015 7:21 PM

  • 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"

    // }

    // }

    private static final String CLIENTSECRET_LOCATION = "/client_secret.json";

    private static final String APPLICATION_NAME = "Your app name";

    private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

    private static final List SCOPES = Arrays.asList(

    "https://www.googleapis.com/auth/drive.file",

    "email",

    "profile");

    private static GoogleAuthorizationCodeFlow flow = null;

    private static final JacksonFactory JSON_FACTORY =

    JacksonFactory.getDefaultInstance();

    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    /**

    * Exception thrown when an error occurred while retrieving credentials.

    */

    public static class GetCredentialsException extends Exception {

    protected String authorizationUrl;

    /**

    * Construct a GetCredentialsException.

    *

    * @param authorizationUrl The authorization URL to redirect the user to.

    */

    public GetCredentialsException(String authorizationUrl) {

    this.authorizationUrl = authorizationUrl;

    }

    Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server

    3 of 10 5/10/2015 7:21 PM

  • /**

    * 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) {

    Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server

    4 of 10 5/10/2015 7:21 PM

  • // 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) {

    Implementing Server-Side Authorization - Drive REST API Google ... https://developers.google.com/drive/web/auth/web-server

    5 of 10 5/10/2015 7:21 PM

  • System.err.println("An error occurred: " + e);

    throw new CodeExchangeException(null);

    }

    }

    /**

    * Send a request to the UserInfo API to retrieve the user's information.

    *

    * @param credentials OAuth 2.0 credentials to authorize the request.

    * @return User's information.

    * @throws NoUserIdException An error occurred.

    */

    static Userinfoplus getUserInfo(Credential credentials)

    throws NoUserIdException {

    Oauth2 userInfoService = new Oauth2.Builder(

    HTTP_TRANSPORT, JSON_FACTORY, credentials)

    .setApplicationName(APPLICATION_NAME)

    .build();

    Userinfoplus userInfo = null;

    try {

    userInfo = userInfoService.userinfo().get().execute();

    } catch (IOException e) {

    System.err.println("An error occurred: " + e);

    }

    if (userInfo != null && userInfo.getId() != null) {

    return userInfo;

    } else {

    throw new NoUserIdException();

    }

    }

    /**

    * Retrieve the authorization URL.

    *

    * @param emailAddress User's e-mail address.

    * @param state State for the authorization URL.

    * @return Authorization URL to redirect the user to.

    * @throws IOException Unable to load client_secret.json.

    */

    public static String getAuthorizationUrl(String emailAddress, String state)

    throws IOException {

    GoogleAuthorizationCodeRequestUrl urlBuilder = getFlow()

    .newAuthorizationUrl()

    .setRedirectUri(REDIRECT_URI)

    .setState(state);

    urlBuilder.set("user_id", emailAddress);

    return urlBuilder.build();

    }

    /**

    * Retrieve credentials using the provided authorization code.

    *

    * This function exchanges the authorization code for an access token and

    * queries the UserInfo API to retrieve the user's e-mail address. If a

    * refresh token has been retrieved along with an access token, it is stored

    * in the application database using the user's e-mail address as key. If no

    * refresh token has been retrieved, the function checks in the application

Recommended

View more >