简体   繁体   中英

Google Cloud StorageException: Anonymous caller does not have storage.objects.create access to the Google Cloud Storage object

I'm trying to upload images to the Google Cloud Storage Client and I get this exception, I've tried searching regarding this but there are no question regarding this issue in android and unable to go forward, here is my code:

MainActivity.Java

public class MainActivity extends AppCompatActivity {

    private String currentPhotoPath;
    private String imageName;
    public static final int REQUEST_IMAGE_CAPTURE = 1;
    private File photoFile = null;
    private String[] permissions;
    public static final int PERMISSION_REQ_CODE = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView= findViewById(R.id.textView);
        permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION};
        acceptPermissions();

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dispatchTakePictureIntent();
            }
        });
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        try {
            photoFile = createImageFile();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this, getPackageName(), photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        String fileName = "temp";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(fileName, ".jpg");
        currentPhotoPath = image.getAbsolutePath();
        imageName = image.getName();
        return image;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try  {
                        UploadObject.uploadObject("project_id", "bucktedname", imageName, currentPhotoPath);                       
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();          
        }
    }

    private void acceptPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[1]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[2]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[3]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[4]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[5]) != PackageManager.PERMISSION_GRANTED)
                requestPermissions(permissions, PERMISSION_REQ_CODE);
            else {
                if ((ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[1]) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[2]) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[3]) != PackageManager.PERMISSION_GRANTED) || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[4]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[5]) != PackageManager.PERMISSION_GRANTED)
                    requestPermissions(permissions, PERMISSION_REQ_CODE);
            }
        }
    }

}

UploadObject.Java

public class UploadObject {
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void uploadObject(
            String projectId, String bucketName, String objectName, String filePath) throws IOException {

        Storage storage = StorageOptions.newBuilder().setProjectId(projectId).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);
    }
}

Logcat:

W/System.err: com.google.cloud.storage.StorageException: Anonymous caller does not have storage.objects.create access to the Google Cloud Storage object.
        at com.google.cloud.storage.spi.v1.HttpStorageRpc.translate(HttpStorageRpc.java:232)
        at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:313)
        at com.google.cloud.storage.StorageImpl$3.call(StorageImpl.java:221)
W/System.err:     at com.google.cloud.storage.StorageImpl$3.call(StorageImpl.java:218)
        at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:105)
        at com.google.cloud.RetryHelper.run(RetryHelper.java:76)
        at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:50)
        at com.google.cloud.storage.StorageImpl.internalCreate(StorageImpl.java:217)
        at com.google.cloud.storage.StorageImpl.create(StorageImpl.java:171)
W/System.err:     at com.example.googlecloudstorgae.UploadObject.uploadObject(UploadObject.java:35)
        at com.example.googlecloudstorgae.MainActivity$2.run(MainActivity.java:111)
        at java.lang.Thread.run(Thread.java:923)
W/System.err: Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
    POST https://storage.googleapis.com/upload/storage/v1/b/"bucket-Name"/o?projection=full&uploadType=multipart
W/System.err: {
      "code" : 401,
      "errors" : [ {
        "domain" : "global",
        "location" : "Authorization",
        "locationType" : "header",
        "message" : "Anonymous caller does not have storage.objects.create access to the Google Cloud Storage object.",
        "reason" : "required"
      } ],
W/System.err:   "message" : "Anonymous caller does not have storage.objects.create access to the Google Cloud Storage object."
    }
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:118)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:37)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:532)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:455)
W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:565)
        at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:310)
        ... 10 more

I've followed the documentation from the official google documentation, this . Any help is appreciated.

It seems like an authorization issue.

"code" : 401,
"message" : "Anonymous caller does not have storage.objects.create access to the Google Cloud Storage object.

You might have to check the access for the user with which you are trying to access the bucket. Either you can check the privileges if you have the dashboard access. OR try performing the same operation using the same json certificate with gsutil .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM