Amazon MWS – request signature calculated does not match the signature provided

Getting the following error message from https://mws.amazonservices.com/:

<Type>Sender</Type>
<Code>SignatureDoesNotMatch</Code>
−
<Message>
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
</Message>

Here is the VB.net code I am using to calculate the request. I have removed the SecretKey and AWSAccessKeyId for security reasons.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim sURL As String = "https://mws.amazonservices.com/"

        Dim sRequest As String = ""
        sRequest &= "Acknowledged=" & Server.UrlEncode("false")
        sRequest &= "&Action=" & Server.UrlEncode("GetReportList")
        sRequest &= "&AWSAccessKeyId=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&Marketplace=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&Merchant=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&SignatureMethod=" & Server.UrlEncode("HmacSHA256")
        sRequest &= "&SignatureVersion=" & Server.UrlEncode("2")
        sRequest &= "&Timestamp=" & Server.UrlEncode(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssCST"))
        sRequest &= "&Version=" & Server.UrlEncode("2009-01-01")

        Dim StringToSign As String = "GETn" & "mws.amazonservices.comn" & "/n" & sRequest
        sRequest &= "&Signature=" & Server.UrlEncode(HashString(StringToSign))

        Response.Write("<a href=""" rel="nofollow noreferrer noopener" & sURL & "?" & sRequest & """>Click here</a>")

    End Sub

    Public Shared Function HashString(ByVal StringToHash As String) As String
        Dim myEncoder As New System.Text.UTF8Encoding
        Dim Key() As Byte = myEncoder.GetBytes("REMOVED-FOR-SECURITY")
        Dim XML() As Byte = myEncoder.GetBytes(StringToHash)
        Dim myHMACSHA256 As New System.Security.Cryptography.HMACSHA256(Key)
        Dim HashCode As Byte() = myHMACSHA256.ComputeHash(XML)
        Return Convert.ToBase64String(HashCode)
    End Function

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you are landing here from Google after starting to work through some of the Amazon documentation, it’s quite likely that you’re seeing the ‘request signature’ error above due to a inadvertent leading or trailing space on your secret access key. Check that first!

Method 2

In my experience, this error just means “One of your parameters is wrong, good luck finding it!” I ran into this error using the S3 SDK. I was trying to upload a file but I mistakenly supplied the full file path (“C:Usersaddaoneimage.png”) as the Key instead of just the file name.

Method 3

The solution was to generate a new Access Key. My first AWSSecretKey had trailing forward slashes on it that probably were causing the issue, while the new one didn’t have any forward slashes and worked.

Method 4

I ran into this problem as well. For me it’s because I accidentally put a / in front of my bucket name.

instead of test/foo/bar I had /test/foo/bar for my bucket name.

Method 5

I found this because I wasn’t doing the URL encoding – it seems this error is returned if any of the parameters passed are invalid – it may have nothing at all to do with the access key.

Method 6

Another thing to check is that each of your parameters likely need to be sorted by ASCII value. “AWSAccessKeyId” parameter should come before “Marketplace”, however “AssociatedTag” should come after “AWSAccessId”.

Method 7

Similar answer to Andrew (accepted answer), but my trailing spaces were not on the keys, but on the metadata for an S3 upload:

using (AmazonS3Client client = new AmazonS3Client(region))
{
    PutObjectRequest putObjectRequest = new PutObjectRequest
    {
        ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256,
        InputStream = stream,
        BucketName = s3Bucket,
        Key = key,
        ContentType = "application/octet-stream",
        Timeout = TimeSpan.FromMinutes(60), //http timeout talking to S3, including upload time.
        ReadWriteTimeout = TimeSpan.FromMinutes(5) //timeout reading the input stream
    };
    if (!string.IsNullOrEmpty(fileName))
        putObjectRequest.Metadata.Add("Name", fileName); 
    PutObjectResponse putObjectResponse = client.PutObject(putObjectRequest);
    // Exception in client.PutObject if fileName has leading spaces in Metadata!
}           

Call stack here:

The request signature we calculated does not match the signature you provided. Check your key and signing method.
at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) in d:Jenkinsjobsv3-stage-releaseworkspaceAWSDotNetPublicsdksrcCoreAmazon.RuntimePipelineErrorHandlerHttpErrorResponseExceptionHandler.cs:line 116
at Amazon.Runtime.Internal.ExceptionHandler`1.Handle(IExecutionContext executionContext, Exception exception) in d:Jenkinsjobsv3-stage-releaseworkspaceAWSDotNetPublicsdksrcCoreAmazon.RuntimePipelineErrorHandlerExceptionHandler.cs:line 38
[...]
at Amazon.Runtime.AmazonServiceClient.Invoke[TRequest,TResponse](TRequest request, IMarshaller`2 marshaller, ResponseUnmarshaller unmarshaller) in d:Jenkinsjobsv3-stage-releaseworkspaceAWSDotNetPublicsdksrcCoreAmazon.RuntimeAmazonServiceClient.cs:line 117
at Amazon.S3.AmazonS3Client.PutObject(PutObjectRequest request) in d:Jenkinsjobsv3-stage-releaseworkspaceAWSDotNetPublicsdksrcServicesS3Generated_bcl45AmazonS3Client.cs:line 3646
at MoveDocumentDataToDisk.AwsRepository.PutObject(RegionEndpoint region, String s3Bucket, String key, String fileName, Stream stream) in C:codeclarinetsupportfilesMoveDocumentDataToDiskMoveDocumentDataToDiskProgram.cs:line 314

Method 8

I ran into the same error message when using WebClient to download a file on an Amazon 3S url.
I blogged about it here:
http://blog.cdeutsch.com/2010/11/net-webclient-403-forbidden-error.html

The final solution I used was found here:
GETting a URL with an url-encoded slash

Method 9

Mine was because I copied environment variables from someone but they just had placeholder text. Hah!

Method 10

This is also encountered when we try to upload a zero byte file. I have opened up a bug here today.

Method 11

I was getting the same ‘calculated does not match’ message when my mistake was related to how my roles were configured

Check your roles, policies and CORS configuration for your bucket to be sure you have permission to use the headers that you are using.

In my case, I had been including the

ACL: 'public-read'

parameter in signing the bucket as well as
xhr.setRequestHeader('x-amz-acl', 'public-read');

while uploading the image.

I was missing the “s3:PutObjectAcl”, permission in my associated Iam user. Here is a policy that worked.

{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Sid": "Stmt12345",
        "Effect": "Allow",
        "Action": [
            "s3:DeleteObject",
            "s3:GetObject",
            "s3:ListBucket",
            "s3:PutObject",
            "s3:PutObjectAcl"
        ],
        "Resource": [
            "arn:aws:s3:::mybucketname/*"
        ],
        "Condition": {
            "StringEquals": {
                "s3:x-amz-acl": [
                    "public-read"
                ]
            }
        }
    }
  ]
}

Method 12

I ran into this problem when I had a wrong URL (it gave me this error sometimes, and sometimes it said they key could no be found, implying a 404 error). These URLS are case sensitive, so make sure you are being exact. I had “.jpg” in my URL, and needed “.JPG”

Method 13

I just ran into this error. I’m using PHP, and ran a scandir() on my directory with my files.

The scandir() function returned . and .. as the first two indexes of the array. After adding a conditional statement in to be sure it doesn’t create a file for these, it worked.

Method 14

This problem may occur for users that have placed the IAM user’s “Password” in the CLI instead of the “Private Access Key”. Where is the “Private Access Key” you may ask? You can’t retrieve it, but you can create a new one via:

  • IAM, Users, Manage Access Keys, Create Access Key
  • Ok, copy the key quick! It is your only chance. 🙂

Method 15

I got the same error with a SubmitFeed call, and after various hours of debugging it turned out that CURL turned my POST request into a PUT request, which made my signature invalid.

It helped a lot to set CURLINFO_HEADER_OUT to 1 via curl_setopt(), so a later call to curl_getinfo() said my request was a PUT request.

So I compared the CURL options in Amazon PHP library to what I did via curl_setopt(), and tataa: the Amazon PHP library does this:

curl_setopt(CURLINFO_HEADER_OUT, 'POST');

(or GET, depending on self::REQUEST_TYPE). Doing the same in my own CURL request turned the request from PUT to POST, so my hashed signature was intact again.

Method 16

I ran into same issue using curl command to upload a zero byte file to S3 presigned url.

I found when remove header -H 'Content-Type: application/octet-stream' then can work.

Method 17

I was using Ruby’s aws-sdk v1 and I was getting this error because I was specifying the content type when calling url_for, following this example on the docs. Removing the content_type parameter on the url_for called solved the problem for me.

Method 18

We were receiving this on a webserver but not in a console app using an old version of the AWS C# SDK (1.5.10.0). Once we upgraded to the most recent it went away.

Method 19

Check your request headers, in my case I was sending something an extra header form the code that I copy pasted (like a noob) containing:

HOST: localhost:8080

Method 20

After lot of struggle, I used the putObject Constructor to upload File instead of inputstream and it worked.
Not sure what was wrong though.

Method 21

PHP: I had problem that when adding a “/” to denote a folder in s3, I was adding it to the bucket name, it seems the PUTOBJECT command of aws-package replaced “/” with “%2F”, so it failed sha256 calculation of the request as it could look:
awsbucket%2Ffolder/filename
but it probably did a pre-calculation of the sha with:
awsbucket/folder/filename

Solution was to pre-add the folder name to the filename instead.

from:
awsbucket/folder
filename
to:
awsbucket
folder/filename

Method 22

I ran into this problem using .net core 2.1.300-preview1 as well. Updating to 2.1.300-rc1 was the solution.

Method 23

1 more answer to the stack: trying to stream data & setting -1 as content length also shows this error

Method 24

I got this error in java because I had the wrong value for AWS_SECRET_ACCESS_KEY … it was incorrectly pointing to my pem file. Instead, I needed to use the secret value for my access key found here: https://console.aws.amazon.com/iam/home?region=us-east-1#/security_credentials.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x