ali haider
ali haider

Reputation: 20202

unable to upload with presigned url on aws s3 with java sdk

I receive a presigned URL to upload to S3 . When i upload given the code below, i am getting a 403 status response. I tried setting the bucket policy to public on the web console but that has not solved the issue. Any other insights on how to fix the issue? i have also tried adding the ACL to PublicREADWRITE.

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("PUT");

    OutputStream out = connection.getOutputStream();

   // OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
    //out.write("This text uploaded as an object via presigned URL.");


    byte[] boundaryBytes = Files.readAllBytes(Paths.get(edmFile));
    out.write(boundaryBytes);
    out.close();

    // Check the HTTP response code. To complete the upload and make the object available,
    // you must interact with the connection object in some way.
    int responseCode = connection.getResponseCode();
    System.out.println("HTTP response code: " + responseCode);

Presigned url:

  private URL getUrl(String bucketName, String objectKey) {

        String clientRegion = "us-east-1";
        java.util.Date expiration = new java.util.Date();
        long expTimeMillis = expiration.getTime();
        expTimeMillis += 1000 * 60 * 10;
        expiration.setTime(expTimeMillis);

        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withCredentials(new ProfileCredentialsProvider())
                .withRegion(clientRegion)
                .build();
        GeneratePresignedUrlRequest generatePresignedUrlRequest =
                new GeneratePresignedUrlRequest(bucketName, objectKey)
                        .withMethod(HttpMethod.GET)
                        .withExpiration(expiration);
        URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

        System.out.println("Pre-Signed URL: " + url.toString());
        return url;
    }

Upvotes: 0

Views: 2155

Answers (1)

Imran
Imran

Reputation: 6235

As discussed, signed Url should exactly match on what you want to do next.

Your pre-signed Url is created with GET operation, that's why upload PUT operation is failing with access denied error.

Try updating the withMethod to PUT.

GeneratePresignedUrlRequest generatePresignedUrlRequest =
                new GeneratePresignedUrlRequest(bucketName, objectKey)
                        .withMethod(HttpMethod.PUT)
                        .withExpiration(expiration);

Upvotes: 1

Related Questions