0

I'm trying to generate a presigned URL with the exact code available on the documentation:

https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/examples-s3-presign.html

PutObjectRequest objectRequest = PutObjectRequest.builder()
                .bucket(bucketName)
                .key(keyName)
                .contentType("text/plain")
                .build();

        PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder()
                .signatureDuration(Duration.ofMinutes(10))
                .putObjectRequest(objectRequest)
                .build();

        PresignedPutObjectRequest presignedRequest = presigner.presignPutObject(presignRequest);


        String myURL = presignedRequest.url().toString();
        System.out.println("Presigned URL to upload a file to: " +myURL);
        System.out.println("Which HTTP method needs to be used when uploading a file: " +
                presignedRequest.httpRequest().method());

        // Upload content to the Amazon S3 bucket by using this URL
        URL url = presignedRequest.url();

        // Create the connection and use it to upload the new object by using the presigned URL
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type","text/plain");
        connection.setRequestMethod("PUT");
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write("This text was uploaded as an object by using a presigned URL.");
        out.close();

        connection.getResponseCode();
        System.out.println("HTTP response code is " + connection.getResponseCode());

    } catch (S3Exception e) {
        e.getStackTrace();
    } catch (IOException e) {
        e.getStackTrace();
    }

but I'm getting an error:

SignatureDoesNotMatch The request signature we calculated does not match the signature you provided. Check your key and signing method.

Any idea why the documentation code is not working? It seems something related to AWS Signature V4. I have no idea

smac2020
  • 9,637
  • 4
  • 24
  • 38
daph111
  • 101
  • 1
  • 8

1 Answers1

0

I just tested this AWS SDK for Java V2 Code example and it works perfectly and generates a Pre-Signed URL -- as shown here which is a screen shot of debugging the code line by line:

enter image description here

The full example is here:

https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndUploadObject.java

Have you used the dependencies shown in the POM file in this Github location?

Other possible issues could be you set your S3 client object to the wrong region or have an issue with the key name as discussed here -- Amazon S3 - How to fix 'The request signature we calculated does not match the signature' error?.

smac2020
  • 9,637
  • 4
  • 24
  • 38