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;
}
}
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();
}
}
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);
}
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());
}
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");
}
Aggregations