Search in sources :

Example 1 with DbxCredential

use of com.dropbox.core.oauth.DbxCredential in project dropbox-sdk-java by dropbox.

the class Main method main.

public static void main(String[] args) throws IOException {
    // Only display important log messages.
    Logger.getLogger("").setLevel(Level.WARNING);
    if (args.length != 3) {
        System.err.println("Usage: COMMAND <app-info-file> <auth-file-output> <mode>");
        System.err.println("");
        System.err.println("<app-info-file>: a JSON file with information about your API app.  Example:");
        System.err.println("");
        System.err.println("  {");
        System.err.println("    \"key\": \"Your Dropbox API app key...\",");
        System.err.println("    \"secret\": \"Your Dropbox API app secret...\"");
        System.err.println("  }");
        System.err.println("");
        System.err.println("  Get an API app key by registering with Dropbox:");
        System.err.println("    https://dropbox.com/developers/apps");
        System.err.println("");
        System.err.println("<auth-file-output>: If authorization is successful, the resulting API");
        System.err.println("  credential will be saved to this file, which can then be used with");
        System.err.println("  other example programs, such as the one in \"examples/account-info\".");
        System.err.println("");
        System.err.println("<mode>: value can only be short_live_token, pkce, scope, or incremental.");
        System.err.println("  short_live_token: authorization will request short_lived_token");
        System.err.println("    together with refresh token and expiration time.");
        System.err.println("  pkce: authorization will run short_live_token without app secret");
        System.err.println("    use that when you have a client side only app without server.");
        System.err.println("  scope: authorization will request specific scope.");
        System.err.println("");
        System.exit(1);
        return;
    }
    String argAppInfoFile = args[0];
    String argAuthFileOutput = args[1];
    // Read app info file (contains app key and app secret)
    DbxAppInfo appInfo;
    try {
        appInfo = DbxAppInfo.Reader.readFromFile(argAppInfoFile);
    } catch (JsonReader.FileLoadException ex) {
        System.err.println("Error reading <app-info-file>: " + ex.getMessage());
        System.exit(1);
        return;
    }
    // Run through Dropbox API authorization process
    DbxAuthFinish authFinish = null;
    switch(args[2]) {
        case "short_live_token":
            authFinish = new ShortLiveTokenAuthorize().authorize(appInfo);
            break;
        case "pkce":
            authFinish = new PkceAuthorize().authorize(appInfo);
            break;
        case "scope":
            authFinish = new ScopeAuthorize().authorize(appInfo);
            break;
        default:
            System.err.println("Error reading <mode> : " + args[2]);
            System.exit(1);
    }
    System.out.println("Authorization complete.");
    System.out.println("- User ID: " + authFinish.getUserId());
    System.out.println("- Account ID: " + authFinish.getAccountId());
    System.out.println("- Access Token: " + authFinish.getAccessToken());
    System.out.println("- Expires At: " + authFinish.getExpiresAt());
    System.out.println("- Refresh Token: " + authFinish.getRefreshToken());
    System.out.println("- Scope: " + authFinish.getScope());
    // Save auth information the new DbxCredential instance. It also contains app_key and
    // app_secret which is required to do refresh call.
    DbxCredential credential = new DbxCredential(authFinish.getAccessToken(), authFinish.getExpiresAt(), authFinish.getRefreshToken(), appInfo.getKey(), appInfo.getSecret());
    File output = new File(argAuthFileOutput);
    try {
        DbxCredential.Writer.writeToFile(credential, output);
        System.out.println("Saved authorization information to \"" + output.getCanonicalPath() + "\".");
    } catch (IOException ex) {
        System.err.println("Error saving to <auth-file-out>: " + ex.getMessage());
        System.err.println("Dumping to stderr instead:");
        DbxCredential.Writer.writeToStream(credential, System.err);
        System.exit(1);
        return;
    }
}
Also used : ShortLiveTokenAuthorize(com.dropbox.core.examples.authorize.ShortLiveTokenAuthorize) DbxAppInfo(com.dropbox.core.DbxAppInfo) JsonReader(com.dropbox.core.json.JsonReader) DbxCredential(com.dropbox.core.oauth.DbxCredential) DbxAuthFinish(com.dropbox.core.DbxAuthFinish) IOException(java.io.IOException) ScopeAuthorize(com.dropbox.core.examples.authorize.ScopeAuthorize) File(java.io.File) PkceAuthorize(com.dropbox.core.examples.authorize.PkceAuthorize)

Example 2 with DbxCredential

use of com.dropbox.core.oauth.DbxCredential in project dropbox-sdk-java by dropbox.

the class DropboxActivity method onResume.

// will use our Short Lived Token.
@Override
protected void onResume() {
    super.onResume();
    SharedPreferences prefs = getSharedPreferences("dropbox-sample", MODE_PRIVATE);
    if (USE_SLT) {
        String serailizedCredental = prefs.getString("credential", null);
        if (serailizedCredental == null) {
            DbxCredential credential = Auth.getDbxCredential();
            if (credential != null) {
                prefs.edit().putString("credential", credential.toString()).apply();
                initAndLoadData(credential);
            }
        } else {
            try {
                DbxCredential credential = DbxCredential.Reader.readFully(serailizedCredental);
                initAndLoadData(credential);
            } catch (JsonReadException e) {
                throw new IllegalStateException("Credential data corrupted: " + e.getMessage());
            }
        }
    } else {
        String accessToken = prefs.getString("access-token", null);
        if (accessToken == null) {
            accessToken = Auth.getOAuth2Token();
            if (accessToken != null) {
                prefs.edit().putString("access-token", accessToken).apply();
                initAndLoadData(accessToken);
            }
        } else {
            initAndLoadData(accessToken);
        }
    }
    String uid = Auth.getUid();
    String storedUid = prefs.getString("user-id", null);
    if (uid != null && !uid.equals(storedUid)) {
        prefs.edit().putString("user-id", uid).apply();
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) DbxCredential(com.dropbox.core.oauth.DbxCredential) JsonReadException(com.dropbox.core.json.JsonReadException)

Example 3 with DbxCredential

use of com.dropbox.core.oauth.DbxCredential in project dropbox-sdk-java by dropbox.

the class Auth method getDbxCredential.

/**
 * @return The result after
 */
public static DbxCredential getDbxCredential() {
    Intent data = AuthActivity.result;
    if (data == null) {
        return null;
    }
    String token = data.getStringExtra(AuthActivity.EXTRA_ACCESS_TOKEN);
    String secret = data.getStringExtra(AuthActivity.EXTRA_ACCESS_SECRET);
    String uid = data.getStringExtra(AuthActivity.EXTRA_UID);
    if (token == null || "".equals(token) || secret == null || "".equals(secret) || uid == null || "".equals(uid)) {
        return null;
    }
    String appKey = data.getStringExtra(AuthActivity.EXTRA_CONSUMER_KEY);
    String refreshToken = data.getStringExtra(AuthActivity.EXTRA_REFRESH_TOKEN);
    long expiresAt = data.getLongExtra(AuthActivity.EXTRA_EXPIRES_AT, -1);
    Long nullableExpiresAt = (expiresAt >= 0) ? expiresAt : null;
    return new DbxCredential(secret, nullableExpiresAt, refreshToken, appKey);
}
Also used : DbxCredential(com.dropbox.core.oauth.DbxCredential) Intent(android.content.Intent)

Example 4 with DbxCredential

use of com.dropbox.core.oauth.DbxCredential in project dropbox-sdk-java by dropbox.

the class DbxClientV2Test method testRefreshBeforeCall.

@Test
public void testRefreshBeforeCall() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig().withHttpRequestor(mockRequestor).build();
    DbxCredential credential = new DbxCredential("accesstoken", 10L, "refresh_token", "appkey", "app_secret");
    DbxClientV2 client = new DbxClientV2(config, credential);
    FileMetadata expected = constructFileMetadate();
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish()).thenReturn(createSuccessRefreshResponse("newToken", 10L)).thenReturn(createSuccessResponse(serialize(expected)));
    when(mockRequestor.startPost(anyString(), anyHeaders())).thenReturn(mockUploader);
    long now = System.currentTimeMillis();
    Metadata actual = client.files().getMetadata(expected.getId());
    verify(mockRequestor, times(2)).startPost(anyString(), anyHeaders());
    assertThat(credential.getAccessToken()).isEqualTo("newToken");
    assertThat(credential.getExpiresAt() > now).isTrue();
    assertThat(actual.getName()).isEqualTo(expected.getName());
    assertWithMessage(actual.getClass().toString()).that(actual instanceof FileMetadata).isTrue();
    assertThat(((FileMetadata) actual).getId()).isEqualTo(expected.getId());
}
Also used : HttpRequestor(com.dropbox.core.http.HttpRequestor) FileMetadata(com.dropbox.core.v2.files.FileMetadata) FileMetadata(com.dropbox.core.v2.files.FileMetadata) Metadata(com.dropbox.core.v2.files.Metadata) DbxCredential(com.dropbox.core.oauth.DbxCredential) Test(org.testng.annotations.Test)

Example 5 with DbxCredential

use of com.dropbox.core.oauth.DbxCredential in project dropbox-sdk-java by dropbox.

the class DbxClientV2Test method testOnlineInvalidToken.

@Test
public void testOnlineInvalidToken() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig().withHttpRequestor(mockRequestor).build();
    DbxCredential credential = new DbxCredential("accesstoken");
    DbxClientV2 client = new DbxClientV2(config, credential);
    FileMetadata expected = constructFileMetadate();
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish()).thenReturn(createInvalidTokenResponse());
    when(mockRequestor.startPost(anyString(), anyHeaders())).thenReturn(mockUploader);
    try {
        client.files().getMetadata(expected.getId());
    } catch (InvalidAccessTokenException ex) {
        verify(mockRequestor, times(1)).startPost(anyString(), anyHeaders());
        assertThat(credential.getAccessToken()).isEqualTo("accesstoken");
        assertThat(ex.getAuthError()).isEqualTo(AuthError.INVALID_ACCESS_TOKEN);
        assertThat(ex.getMessage()).isEqualTo("");
        return;
    }
    fail("API v2 call should throw exception");
}
Also used : HttpRequestor(com.dropbox.core.http.HttpRequestor) FileMetadata(com.dropbox.core.v2.files.FileMetadata) DbxCredential(com.dropbox.core.oauth.DbxCredential) Test(org.testng.annotations.Test)

Aggregations

DbxCredential (com.dropbox.core.oauth.DbxCredential)13 HttpRequestor (com.dropbox.core.http.HttpRequestor)9 FileMetadata (com.dropbox.core.v2.files.FileMetadata)9 Test (org.testng.annotations.Test)9 Metadata (com.dropbox.core.v2.files.Metadata)6 JsonReader (com.dropbox.core.json.JsonReader)2 Intent (android.content.Intent)1 SharedPreferences (android.content.SharedPreferences)1 DbxAppInfo (com.dropbox.core.DbxAppInfo)1 DbxAuthFinish (com.dropbox.core.DbxAuthFinish)1 DbxException (com.dropbox.core.DbxException)1 DbxRequestConfig (com.dropbox.core.DbxRequestConfig)1 PkceAuthorize (com.dropbox.core.examples.authorize.PkceAuthorize)1 ScopeAuthorize (com.dropbox.core.examples.authorize.ScopeAuthorize)1 ShortLiveTokenAuthorize (com.dropbox.core.examples.authorize.ShortLiveTokenAuthorize)1 JsonReadException (com.dropbox.core.json.JsonReadException)1 DbxClientV2 (com.dropbox.core.v2.DbxClientV2)1 AuthError (com.dropbox.core.v2.auth.AuthError)1 FullAccount (com.dropbox.core.v2.users.FullAccount)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1