You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android端使用Google Cloud Storage上传图片时出现Anonymous caller无storage.objects.create权限异常的求助

Solution for GCS Anonymous Access Error on Android

The error Anonymous caller does not have storage.objects.create access to the Google Cloud Storage object happens because your Android app is trying to access Google Cloud Storage (GCS) without any authentication. The current code initializes the GCS client anonymously, which doesn't have permission to write to your bucket. Here's how to fix this specifically for Android:

Step 1: Add Authentication to Your GCS Client

On Android, you can use a service account key to authenticate the GCS client (note: for production, consider more secure methods like Google Sign-In, but this will solve the immediate issue):

  1. Download your service account JSON key from the Google Cloud Console:
    • Go to IAM & Admin > Service Accounts
    • Select your service account, go to Keys > Add Key > Create new key
    • Choose JSON format and download the file
  2. Place the JSON file in your Android project's src/main/assets directory (create the assets folder if it doesn't exist)
  3. Update your UploadObject.java to load the credentials:
public class UploadObject {
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void uploadObject(
            String projectId, String bucketName, String objectName, String filePath, Context context) throws IOException {
        // Load service account credentials from assets
        InputStream credentialsStream = context.getAssets().open("service-account-key.json");
        GoogleCredentials credentials = GoogleCredentials.fromStream(credentialsStream);
        
        // Initialize Storage client with authentication
        Storage storage = StorageOptions.newBuilder()
                .setProjectId(projectId)
                .setCredentials(credentials)
                .build()
                .getService();
        
        BlobId blobId = BlobId.of(bucketName, objectName);
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
        storage.create(blobInfo, Files.readAllBytes(Paths.get(filePath)));
        System.out.println(
                "File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
    }
}
  1. Update the call in MainActivity to pass the context:
UploadObject.uploadObject("project_id", "bucktedname", imageName, currentPhotoPath, MainActivity.this);

Step 2: Grant Permissions to the Service Account

Make sure your service account has the right permissions to write to the GCS bucket:

  • Go to your GCS bucket in the Google Cloud Console
  • Click Permissions > Add
  • Enter the email address of your service account
  • Assign the Storage Object Creator role (use this instead of broader roles like Storage Admin for least privilege)
  • Save the changes

Additional Notes

  • Security Warning: Never commit the service account JSON key to public code repositories (like GitHub). Add it to your .gitignore file to avoid accidental exposure.
  • Production Best Practices: For production apps, avoid using service account keys directly in the client. Instead, use:
    • Google Sign-In to authenticate users and grant them GCS access via IAM
    • Firebase Storage (built on GCS), which handles authentication seamlessly with Firebase Auth
  • Permission Check Cleanup: Your acceptPermissions() method has messy logic that might not request permissions correctly. Simplify it like this:
private void acceptPermissions() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        boolean permissionsNeeded = false;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsNeeded = true;
                break;
            }
        }
        if (permissionsNeeded) {
            requestPermissions(permissions, PERMISSION_REQ_CODE);
        }
    }
}

内容的提问来源于stack exchange,提问作者krish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:13:15