Programing

Amazon MWS-계산 된 요청 서명이 제공된 서명과 일치하지 않습니다.

lottogame 2020. 11. 16. 07:45
반응형

Amazon MWS-계산 된 요청 서명이 제공된 서명과 일치하지 않습니다.


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>

다음은 요청을 계산하는 데 사용하는 VB.net 코드입니다. 보안상의 이유로 SecretKey 및 AWSAccessKeyId를 제거했습니다.

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 = "GET\n" & "mws.amazonservices.com\n" & "/\n" & sRequest
        sRequest &= "&Signature=" & Server.UrlEncode(HashString(StringToSign))

        Response.Write("<a href=""" & 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

일부 Amazon 문서 작업을 시작한 후 Google에서 여기에 도착하는 경우 보안 액세스 키의 우연한 선행 또는 후행 공백으로 인해 위의 '서명 요청'오류가 표시 될 가능성이 큽니다. 먼저 확인하십시오!


제 경험상이 오류는 "매개 변수 중 하나가 잘못되었습니다. 행운을 빕니다!"를 의미합니다. S3 SDK를 사용하여이 오류가 발생했습니다. 파일을 업로드하려고했지만 파일 이름 대신 전체 파일 경로 ( "C : \ Users \ addaone \ image.png")를 키로 잘못 입력했습니다.


이 문제도 발생했습니다. 저에게는 실수로 버킷 이름 앞에 /를 입력했기 때문입니다.

test / foo / bar 대신 버킷 이름에 / test / foo / bar가 있습니다.


해결책은 새 액세스 키를 생성하는 것이 었습니다. 내 첫 번째 AWSSecretKey에는 아마도 문제를 일으키는 슬래시가 뒤 따르고 있었지만 새 AWSSecretKey에는 슬래시가 없었고 작동했습니다.


URL 인코딩을 수행하지 않았기 때문에 이것을 발견했습니다. 전달 된 매개 변수 중 하나라도 유효하지 않은 경우이 오류가 반환되는 것 같습니다. 액세스 키와 전혀 관련이 없을 수 있습니다.


Andrew에 대한 유사한 답변 (수락 된 답변)이지만 후행 공백은 키가 아니라 S3 업로드의 메타 데이터에 있습니다.

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!
}           

여기에서 스택 호출 :

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:\Jenkins\jobs\v3-stage-release\workspace\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\ErrorHandler\HttpErrorResponseExceptionHandler.cs:line 116
at Amazon.Runtime.Internal.ExceptionHandler`1.Handle(IExecutionContext executionContext, Exception exception) in d:\Jenkins\jobs\v3-stage-release\workspace\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\ErrorHandler\ExceptionHandler.cs:line 38
[...]
at Amazon.Runtime.AmazonServiceClient.Invoke[TRequest,TResponse](TRequest request, IMarshaller`2 marshaller, ResponseUnmarshaller unmarshaller) in d:\Jenkins\jobs\v3-stage-release\workspace\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\AmazonServiceClient.cs:line 117
at Amazon.S3.AmazonS3Client.PutObject(PutObjectRequest request) in d:\Jenkins\jobs\v3-stage-release\workspace\AWSDotNetPublic\sdk\src\Services\S3\Generated\_bcl45\AmazonS3Client.cs:line 3646
at MoveDocumentDataToDisk.AwsRepository.PutObject(RegionEndpoint region, String s3Bucket, String key, String fileName, Stream stream) in C:\code\clarinetsupportfiles\MoveDocumentDataToDisk\MoveDocumentDataToDisk\Program.cs:line 314

확인해야 할 또 다른 사항은 각 매개 변수가 ASCII 값으로 정렬되어야한다는 것입니다. "AWSAccessKeyId"파라미터는 "Marketplace"앞에 와야하지만 "AssociatedTag"는 "AWSAccessId"뒤에 와야합니다.


WebClient를 사용하여 Amazon 3S URL에서 파일을 다운로드 할 때 동일한 오류 메시지가 나타납니다. 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


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


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


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"
                ]
            }
        }
    }
  ]
}

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"


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.


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. :)

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.


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.


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.


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.


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

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


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


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

참고URL : https://stackoverflow.com/questions/2777078/amazon-mws-request-signature-calculated-does-not-match-the-signature-provided

반응형