Need to see if your shared folder is taking up space on your dropbox 👨💻? Find out how to check here.
Forum Discussion
Ghost Mjrm
3 years agoExplorer | Level 4
How can i get lifetime Access Token
i have android app connected to my Dropbox folder using access token but every 4 hour should i edit my code and input the new access token is there any method to make the app working 24h without any ...
- 3 years ago
Ghost Mjrm, Be more careful when inspecting the code.
Ghost Mjrm wrote:
... there is no offline ...Hm..🤔 Let's see where the OAuth starts here and what actually gets executed here. 🧐 Are you still thinking "there is no offline"? 🙂
Ghost Mjrm wrote:
... or refresh token exampleLet's see where OAuth finish here and what actually it executes here. Ahhh... where was this refresh token... 😉
Keep more attention on code reading.
Ghost Mjrm
2 years agoExplorer | Level 4
there is my main code
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int CAMERA_PERMISSION_REQUEST = 100;
private static final String[] REQUIRED_CAMERA_PERMISSIONS = new String[]{Manifest.permission.CAMERA};
private static final String DROPBOX_APP_KEY = "hc2p6uj44p9pyoc";
private static final String DROPBOX_APP_SECRET = "i cannot show this";
private static final String DROPBOX_REDIRECT_URI = "https://auth-finish";
private String DROPBOX_ACCESS_TOKEN = null;
private PreviewView previewView;
private ImageCapture imageCapture;
private TextView addressTextView;
private ExecutorService cameraExecutor = Executors.newSingleThreadExecutor();
private FusedLocationProviderClient fusedLocationProviderClient;
private Geocoder geocoder;
// Add latitude and longitude variables
private double latitudeValue;
private double longitudeValue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previewView = findViewById(R.id.previewView);
ImageButton captureButton = findViewById(R.id.captureButton);
ImageButton leftCornerButton = findViewById(R.id.leftCornerButton);
addressTextView = findViewById(R.id.addressTextView);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
geocoder = new Geocoder(this, Locale.getDefault());
captureButton.setOnClickListener(this);
leftCornerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initiateDropboxAuthorization();
}
});
addressTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditAddressDialog();
}
});
if (allPermissionsGranted()) {
startCamera();
getLastLocation();
} else {
ActivityCompat.requestPermissions(this, REQUIRED_CAMERA_PERMISSIONS, CAMERA_PERMISSION_REQUEST);
}
// Initialize Dropbox access token if available
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
DROPBOX_ACCESS_TOKEN = prefs.getString("dropboxAccessToken", null);
// Check if the app was opened with a Dropbox authorization callback
handleDropboxAuthorizationCallback(getIntent());
}
// Override onNewIntent to handle the Dropbox authorization callback
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// Log the received intent data for debugging
Log.d("Dropbox", "Received new intent: " + intent);
// Extract and log the data URI
Uri data = intent.getData();
Log.d("Dropbox", "Intent data URI: " + data);
if (data != null && data.toString().startsWith(DROPBOX_REDIRECT_URI)) {
// Authorization successful, extract the authorization code
String code = data.getQueryParameter("code");
// Log the authorization code for debugging
Log.d("Dropbox", "Authorization Code: " + code);
// Now, exchange the authorization code for an access token and refresh token
exchangeAuthorizationCodeForTokens(code);
}
}
private void initiateDropboxAuthorization() {
// Construct the Dropbox authorization URL
String authorizationUrl = "https://www.dropbox.com/oauth2/authorize" +
"?client_id=" + DROPBOX_APP_KEY +
"&response_type=code" +
"&token_access_type=offline" +
"&state=myState" + // Replace with your own state
"&redirect_uri=" + DROPBOX_REDIRECT_URI;
// Open the authorization URL in a web browser or WebView
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(authorizationUrl));
startActivity(browserIntent);
}
private String performPostRequest(String requestUrl, String urlParameters) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
connection.setDoOutput(true);
// Log the request details
Log.d("Dropbox", "POST Request URL: " + requestUrl);
Log.d("Dropbox", "POST Request Body: " + urlParameters);
// Write the request body
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(urlParameters);
wr.flush();
}
// Get the response
try (InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
// Log the response
Log.d("Dropbox", "POST Response: " + response.toString());
return response.toString();
}
} catch (Exception e) {
// Log any exceptions
Log.e("Dropbox", "Error in HTTP request: " + e.getMessage());
return null;
}
}
private void handleDropboxAuthorizationCallback(Intent intent) {
// Log the received intent for debugging
Log.d("Dropbox", "Handling Dropbox Authorization Callback Intent: " + intent);
Uri data = intent.getData();
if (data != null && data.toString().startsWith(DROPBOX_REDIRECT_URI)) {
// Authorization successful, extract the authorization code
String code = data.getQueryParameter("code");
// Log the authorization code for debugging
Log.d("Dropbox", "Authorization Code: " + code);
// Now, exchange the authorization code for an access token and refresh token
exchangeAuthorizationCodeForTokens(code);
} else {
// Log a message if the intent data is unexpected
Log.d("Dropbox", "Invalid Dropbox Authorization Callback Intent Data: " + data);
}
}
private void exchangeAuthorizationCodeForTokens(String code) {
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
String url = "https://api.dropbox.com/oauth2/token";
String requestBody = "code=" + params[0] +
"&grant_type=authorization_code" +
"&client_id=" + DROPBOX_APP_KEY +
"&client_secret=" + DROPBOX_APP_SECRET +
"&redirect_uri=" + DROPBOX_REDIRECT_URI;
// Log the request details
Log.d("Dropbox", "Token Exchange Request URL: " + url);
Log.d("Dropbox", "Token Exchange Request Body: " + requestBody);
// Perform the POST request and obtain the JSON response
String jsonResponse = performPostRequest(url, requestBody);
// Log the response
Log.d("Dropbox", "Token Exchange Response: " + jsonResponse);
// Parse the JSON response to extract access and refresh tokens
JSONObject jsonObject = new JSONObject(jsonResponse);
DROPBOX_ACCESS_TOKEN = jsonObject.getString("access_token");
// Log the obtained access token
Log.d("Dropbox", "Access Token Obtained: " + DROPBOX_ACCESS_TOKEN);
// Save the Dropbox access token
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
prefs.edit().putString("dropboxAccessToken", DROPBOX_ACCESS_TOKEN).apply();
} catch (Exception e) {
// Log any exceptions
Log.e("Dropbox", "Error in token exchange: " + e.getMessage());
}
return null;
}
}.execute(code);
}
private void uploadToDropbox(File photoFile) {
if (photoFile == null || !photoFile.exists()) {
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error: Photo file does not exist", Toast.LENGTH_SHORT).show());
return;
}
if (DROPBOX_ACCESS_TOKEN == null) {
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error: Dropbox access token is null", Toast.LENGTH_SHORT).show());
return;
}
DbxRequestConfig config = DbxRequestConfig.newBuilder("Decamera").build();
DbxClientV2 client = new DbxClientV2(config, DROPBOX_ACCESS_TOKEN);
try {
String remotePath = "/Decamera/" + photoFile.getName();
try (InputStream in = new FileInputStream(photoFile)) {
FileMetadata metadata = client.files().uploadBuilder(remotePath)
.withMode(WriteMode.ADD)
.uploadAndFinish(in);
runOnUiThread(() -> {
Toast.makeText(MainActivity.this, "Photo uploaded to Dropbox", Toast.LENGTH_SHORT).show();
// Log metadata information
Log.d("Dropbox", "File uploaded. Metadata: " + metadata.toString());
});
}
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error uploading to Dropbox: " + e.getMessage(), Toast.LENGTH_SHORT).show());
}
}
Здравко
2 years agoLegendary | Level 20
Hm..🤔 Are you still trying some sort of AI? 🧐 Ghost Mjrm, come on... 😁 I believe you have your own; use it! 😉
- Ghost Mjrm2 years agoExplorer | Level 4
im not using ai just to copy paste its help to understand the main code to how to exchange authorized code with access token using the app key and app secret and teach me to constructor the link and make post and request method im not using it blindly and its help to create log statments to dedicate the error in the logcat its a powerful but at the end i got upload to dropbox success message but and im 100% sure that the Decamera folder name is correct and app key app secret correct so where is the problem i cannot find it
- Здравко2 years agoLegendary | Level 20
Ghost Mjrm wrote:... so where is the problem i cannot find it
Ah..🙋 If that's fine for you, you can use it in such a way, of course. In such a case you can remove the "offline" declaration for the access type since you're not using it in fact. So big part of entire discussion seems meaningless - you don't need long term access since the posted cover your demands. 🙂 Ok, all done.
- Ghost Mjrm2 years agoExplorer | Level 4Thank you for your support
- Ghost Mjrm2 years agoExplorer | Level 4
i have remove the offline access type and same problem successfully upload to dropbox but there is no nothing in the dropbox app
private void initiateDropboxAuthorization() {
// Construct the Dropbox authorization URL
String authorizationUrl = "https://www.dropbox.com/oauth2/authorize" +
"?client_id=" + DROPBOX_APP_KEY +
"&response_type=code" +
"&state=myState" + // Replace with your own state
"&redirect_uri=" + DROPBOX_REDIRECT_URI;
// Open the authorization URL in a web browser or WebView
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(authorizationUrl));
startActivity(browserIntent);
} - Здравко2 years agoLegendary | Level 20
No, 'offline' access type just adds refresh token to response, nothing else! Something that you're ignoring in your code completely so far. So that cannot be a reason. Are you sure you have uploaded to the same account? 🙃
- Ghost Mjrm2 years agoExplorer | Level 4Yeah im sure but its possible that the obtained access token belong to another person ? Not me
- Здравко2 years agoLegendary | Level 20
In other words, you're not sure - make it sure! 😉
- Ghost Mjrm2 years agoExplorer | Level 4I have recheck that the app key app secret belong to me it cannot be to another one but i think the authorisation had a configuration problem what do you think
- Здравко2 years agoLegendary | Level 20
I think you should NOT mess the application ownership with the account one! They are different things in general (can coincide of course), but you assume they are the same thing always - something wrong. I'm pretty sure your account is different (my questions above are rhetoric). 😉
- Ghost Mjrm2 years agoExplorer | Level 4
i did not understand what you mean but you make me remember about the account by mention you the account word up there
so i opened the app and instead of using a new account in the app ive used the one that belong to me the original one
but in this case when someone used my app should sign in also in my account when press on the oauth 2 operation to obtain new access token
- Здравко2 years agoLegendary | Level 20
😁 In this case (following your words) when someone uses your application should sign in in the same account when pass on the OAuth 2 operation where will look for the file uploaded (no in other account, like you did). 😉
- Ghost Mjrm2 years agoExplorer | Level 4I thought that the user can use any email to upload the file to my dropbox server app because simply using my app key and app secret that I configured in my code
- Здравко2 years agoLegendary | Level 20
Yes, user can do it and the file will get to the account matching this email (whoever is the owner). The same like when you use the official Dropbox application. Where a file put in Dropbox folder goes? 🧐 To your Dropbox account or to account own by some of the application' developers (i.e. Dropbox staff)? 🤔😄
- Ghost Mjrm2 years agoExplorer | Level 4
i understand you but where is the point of my app key and app secret in my code if the photo uploaded goes to the user dropbox account not my dropbox account
did you understand me the photo goes to the dropbox account that the user signed with it
during the oauth 2 process
you know in the authorized request it request from the user to sign in in dropbox 'in the browser'
- Ghost Mjrm2 years agoExplorer | Level 4
look what chat gpt answere me and i find this very logical:
in step number 3 During the user authentication process is the user should sign in using my dropbox accountChatGPTNo, the user should not sign in with your Dropbox account during the authentication process. Instead, the authentication process involves the user signing in with their own Dropbox account. Here's how it typically works:
User Initiates Authentication:
- The user interacts with your app, and your app initiates the Dropbox authentication process.
Redirect to Dropbox for Authorization:
- Your app constructs an authorization URL using your app's key and secret and redirects the user to the Dropbox website.
- The user signs in with their own Dropbox account on the Dropbox website.
- Здравко2 years agoLegendary | Level 20
Hm..🤔 Ok, how the user would know whether the access to their own data is correctly providing to selected code (your application) and not some fake or malicious code? 🧐 On other side, how Dropbox API would ensure the token is provided to correct user and not to some "men in middle"?
PS: OMG...🤦 Is your brain dysfunctional? By the way, your AI (ChatGPT) answer is NOT entirely correct (again), something that should not surprise you, but...
- Ghost Mjrm2 years agoExplorer | Level 4
ok then for security reason should the user sign with my own account to i get the photo
- Ghost Mjrm2 years agoExplorer | Level 4
how to i know this stuff about man in the middle and that things without any background on it no my brain work fine but chatgpt give me answer and you give me different one
and of my small knowledge im here to ask and learn not to proof myself
- Ghost Mjrm2 years agoExplorer | Level 4+ this app i don't want to publish it to the public
And I don’t want unknown user to use it so no one said about the security and this stuff
You can simplify the discussion by saying it’s protocol from the dropbox sdk to protect the user and not using „mindless“ word - Здравко2 years agoLegendary | Level 20
Ghost Mjrm wrote:... im here to ask and learn not to proof myself
Ok, then it's easy 😉, just learn and not try to put non-trusted knowledge (something against TOS of this forum by the way). In this context let see:
Ghost Mjrm wrote:Redirect to Dropbox for Authorization:
- Your app constructs an authorization URL using your app's key and secret and redirects the user to the Dropbox website.
Do you use any secret in your authorization URL? 🧐 How many you should know to figure out it's incorrect? 🤷 - just an example. Where app secret is used in? Just take a look in your code - you don't need to proof yourself or something similar. Again, what you'll believe in? 🙂🤫
- Ghost Mjrm2 years agoExplorer | Level 4
i have noticed to this before that there is no app secret in the authorization URL but in the next step in exchange authorization code for token my app secret IT HAS ALREADY BEEN USED
private void exchangeAuthorizationCodeForTokens(String code) {
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
String url = "https://api.dropbox.com/oauth2/token";
String requestBody = "code=" + params[0] +
"&grant_type=authorization_code" +
"&client_id=" + DROPBOX_APP_KEY +
"&client_secret=" + DROPBOX_APP_SECRET +
"&redirect_uri=" + DROPBOX_REDIRECT_URI; - Здравко2 years agoLegendary | Level 20
Would you like to learn or to proof... not very clear what? 🤔 Might be current ChatGPT stupidity...
Ghost Mjrm wrote:i have noticed to this before that there is no app secret in the authorization URL but in the next step in exchange authorization code for token my app secret IT HAS ALREADY BEEN USED ...
And.. what? Is app secret used in URL or not? 🧐 Yes it's used, of course. What would it exist for otherwise? 🙂 By the way, as already mentioned in current discussion, secret is optional in some cases (when correct token receiving can be guaranteed in other way).
- Ghost Mjrm2 years agoExplorer | Level 4
i don't want to prove something i admit that i got incorrect information from chatgpt but my brain is not dysfunctional i just got confused because the different answers
you were able to help without using hurtful words to the other party - Здравко2 years agoLegendary | Level 20
Ok, sorry, the words just lipped out. I just don't know how to say that such sources are unreliable and how many time to repeat that so it would reach to you. Even more you should be more critical and shouldn't accept such things so... naively believing in them, even when clearly visible they are incorrect. As I said, you're violating TOS too!
AI of any kind will never replace humans intelligence. Don't try replace your own intelligence with something that cannot be better (even in theory). AI could be a good tool, but never replacement.
Good luck.
- Ghost Mjrm2 years agoExplorer | Level 4Thank you for your advice it came at the right time
Good luck to you too
About Dropbox API Support & Feedback
Find help with the Dropbox API from other developers.
The Dropbox Community team is active from Monday to Friday. We try to respond to you as soon as we can, usually within 2 hours.
If you need more help you can view your support options (expected response time for an email or ticket is 24 hours), or contact us on X, Facebook or Instagram.
For more info on available support options for your Dropbox plan, see this article.
If you found the answer to your question in this Community thread, please 'like' the post to say thanks and to let us know it was useful!