amzn / selling-partner-api-models

This repository contains OpenAPI models for developers to use when developing software to call Selling Partner APIs.
Apache License 2.0
618 stars 741 forks source link

Access to requested resource is denied #699

Closed phamanh195 closed 3 years ago

phamanh195 commented 4 years ago

Hi, I am trying the new SP-API and I met the issue about authorization when call request. Step I did:

  1. Create IAM user, role, permission.. etc and get access key, secret access key.
  2. Use IAM, access key, secret access key to create app and get access token as well as refresh token.
  3. Use this access token to sign the API request.

Headers included: host;user-agent;x-amz-access-token;x-amz-date Canonical request: """ GET /feeds/2020-09-04/feeds

host:sellingpartnerapi-na.amazon.com user-agent: { user-agent } x-amz-access-token: { my-access-token } x-amz-date:20201013T024957Z

host;user-agent;x-amz-access-token;x-amz-date e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 """

Authorize header: """ AWS4-HMAC-SHA256 Credential={ access-key-when-create-IAM }/20201013/us-east-1/execute-api/aws4_request, SignedHeaders=host;user-agent;x-amz-access-token;x-amz-date, Signature={ signature } """

And I always meet authorize issue: Response: """ { "errors": [ { "message": "Access to requested resource is denied.", "code": "Unauthorized", "details": "" } ] } """ There is no detail information. Is this a server side errors or I missed out something when submit the request? Could you please help me to address this issue?

ahlmackie commented 4 years ago

I am also getting this error, as are many other people. Raise a case in seller central and add the amazon request-ids for the reponse for them to review. There is a bit of queue / backlog though!

Would be interested if anyone who is self authorising has managed to get access since the offical release? I even tried the hybrid approach using my MWS credientials and got same access error response..

phamanh195 commented 4 years ago

@ahlmackie In my case, it seems the application does not have necessary roles or permissions. I have addressed by adding permissions policies in IAM management > User > Permissions and luckily it work. I hope it make sense for you.

ahlmackie commented 4 years ago

It looks like the guidance on the docs around adding a role doesnt seem to work (or I have messed it up somehow). The work around is to add the policy directly the user as per phamanh195 suggestion:

IAM Management Console => users => select user => add inline policy => click on JSON tab => add the following:

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:::*" } ] }

Appreciate it is not best practices, but i've got access now.

p.s. i have removed the policy and it has defaulted back to the authorization error above

deekay00 commented 4 years ago

i was getting the same error and @ahlmackie workaround worked for me too. i was doing the self authorization option.

parvathm commented 4 years ago

Hi,

In response to reported issues about access denied and IAM policy we are working to clarify this in our dev guide . Meanwhile If you are using IAM role while registering your application the policy should be attached to the IAM role and If you are using IAM user policy should be attached to the IAM user.

If you are using IAM role in the application registration make sure you are using credentials along with STS token to make a request. Please refer here for more details: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html

If you are following everything but still receiving access denied please open a case using this contact us https://sellercentral.amazon.com/gp/mws/contactus.html? and provide us request id, time stamp for quick resolution."

Thanks, Parvathm MWS Support.

girija45701 commented 4 years ago

Do we have some clear documentation. I am new to the SP-API and AWS. I followed the steps in this https://github.com/amzn/selling-partner-api-docs/blob/main/guides/developer-guide/SellingPartnerApiDeveloperGuide.md#registering-your-selling-partner-api-application to set up user, role & policies but it threw the "Access to resource denied error" as everyone gets. My application client was mapped to IAM role.

Now based on the observations here , i added a new inline policy directly under the user , created a new application client mapped to user but the error is the same there as well.

Now based on the suggestion to use the assume role AWS STS (if using role mapped client), i saw the link https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html, but it throws error as signature does not match. I am using the C# library given at https://github.com/amzn/selling-partner-api-models/tree/main/clients/sellingpartner-api-aa-csharp (with some changes) but still not able to make it work.

Can someone please help. I am new to all this so if the solution is pretty straight forward and i am missing something please let me know. If there is an example there (I found lot of examples using AWS SDK but i do not want to use that) please let me know.

I am using self authorization using refresh token to get access token.

Thanks in advance..

rogersv commented 4 years ago

Do we have some clear documentation. I am new to the SP-API and AWS. I followed the steps in this https://github.com/amzn/selling-partner-api-docs/blob/main/guides/developer-guide/SellingPartnerApiDeveloperGuide.md#registering-your-selling-partner-api-application to set up user, role & policies but it threw the "Access to resource denied error" as everyone gets. My application client was mapped to IAM role.

Now based on the observations here , i added a new inline policy directly under the user , created a new application client mapped to user but the error is the same there as well.

Now based on the suggestion to use the assume role AWS STS (if using role mapped client), i saw the link https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html, but it throws error as signature does not match. I am using the C# library given at https://github.com/amzn/selling-partner-api-models/tree/main/clients/sellingpartner-api-aa-csharp (with some changes) but still not able to make it work.

Can someone please help. I am new to all this so if the solution is pretty straight forward and i am missing something please let me know. If there is an example there (I found lot of examples using AWS SDK but i do not want to use that) please let me know.

I am using self authorization using refresh token to get access token.

Thanks in advance..

  • Shankar

I think you might be missing the x-amz-security-token in the header. It should contain the token you got from the assume role. See https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html.

girija45701 commented 4 years ago

Do we have some clear documentation. I am new to the SP-API and AWS. I followed the steps in this https://github.com/amzn/selling-partner-api-docs/blob/main/guides/developer-guide/SellingPartnerApiDeveloperGuide.md#registering-your-selling-partner-api-application to set up user, role & policies but it threw the "Access to resource denied error" as everyone gets. My application client was mapped to IAM role. Now based on the observations here , i added a new inline policy directly under the user , created a new application client mapped to user but the error is the same there as well. Now based on the suggestion to use the assume role AWS STS (if using role mapped client), i saw the link https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html, but it throws error as signature does not match. I am using the C# library given at https://github.com/amzn/selling-partner-api-models/tree/main/clients/sellingpartner-api-aa-csharp (with some changes) but still not able to make it work. Can someone please help. I am new to all this so if the solution is pretty straight forward and i am missing something please let me know. If there is an example there (I found lot of examples using AWS SDK but i do not want to use that) please let me know. I am using self authorization using refresh token to get access token. Thanks in advance..

  • Shankar

I think you might be missing the x-amz-security-token in the header. It should contain the token you got from the assume role. See https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html.

rogersv,

Thanks for replying. when you say i am missing the x-amz-security-token, yes, but i am having trouble getting the token from calling the assume role api. When i call the assume role api i get the error "signature does not match". I am using RestSharp but somehow not able to figure the AssumeRoleAPI call. Do we have any sample for the AssumeRole API (preferably C#) which does not use Amazon SDK ?

I am attaching the small Windows application (C#) which i am using for reference. Not sure what i am doing wrong, but a little help would do to point me in right direction.

AssumeRole.zip

rogersv commented 4 years ago

Hard to know from your description but it could be that you forgot to sign the posted content. Note the X-Amz-Content-Sha256 in

var client = new RestClient("https://sts.amazonaws.com");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("X-Amz-Content-Sha256", "xxxxxxxxxxxxxxxxxx");
request.AddHeader("X-Amz-Date", "xxxxxxxxxx");
request.AddHeader("Authorization", "AWS4-HMAC-SHA256 Credential=xxxxxxxxxxxx/xxxxxx/us-east-1/sts/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=xxxxxxxxxxxxxxxxx");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("Action", "AssumeRole");
request.AddParameter("RoleArn", "xxxxxxxxxxxx");
request.AddParameter("Version", "2011-06-15");
request.AddParameter("RoleSessionName", "xxxxxxxxxxxxxxxx");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
girija45701 commented 4 years ago

var client = new RestClient("https://sts.amazonaws.com"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("X-Amz-Content-Sha256", "xxxxxxxxxxxxxxxxxx"); request.AddHeader("X-Amz-Date", "xxxxxxxxxx"); request.AddHeader("Authorization", "AWS4-HMAC-SHA256 Credential=xxxxxxxxxxxx/xxxxxx/us-east-1/sts/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=xxxxxxxxxxxxxxxxx"); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddParameter("Action", "AssumeRole"); request.AddParameter("RoleArn", "xxxxxxxxxxxx"); request.AddParameter("Version", "2011-06-15"); request.AddParameter("RoleSessionName", "xxxxxxxxxxxxxxxx"); IRestResponse response = client.Execute(request); Console.WriteLine(response.Content);

rogersv,

Thanks again for reply. I am signing the request. If you see the attached application you will see this call "accessTokenRequest = signer.Sign(accessTokenRequest, host);" where the signing of the whole request happens.

When you say i am missing "X-Amz-Content-Sha256" what should i use in that ? Is it the signature?

Do we have a sample to follow.

rogersv commented 4 years ago

I did not use a library so I am not sure how they work. I created the call myself. The only docs I could find right now is https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html. You will need to hash the data that you send and add that hash to the header x-amz-content-sha256. That header is also used in the signing process.

girija45701 commented 4 years ago

I did not use a library so I am not sure how they work. I created the call myself. The only docs I could find right now is https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html. You will need to hash the data that you send and add that hash to the header x-amz-content-sha256. That header is also used in the signing process.

Got it to work. Finally used the .NET Token SDK of the AWS. The problem is that we do not find much examples for the .NET side of things.

Thanks for the help.

voronytskyi commented 4 years ago

@girija45701 can you pls provide sample code implementation with .NET Token SDK?

girija45701 commented 4 years ago

Hi,

I used the AWSSDK.Core and AWSSDK.Security token as reference (nugget) and below is the code

var credentials = new BasicAWSCredentials(, ); AmazonSecurityTokenServiceClient client = new AmazonSecurityTokenServiceClient(credentials, );

            var assumeRoleRequest = new AssumeRoleRequest()
            {
                DurationSeconds = 3600,
                Policy = <The policy JSON>,
                RoleArn = <The Role full ARN>,
                RoleSessionName = string.Format(Constants.RoleSessionPrefixFormat, DateTime.UtcNow.ToString(Constants.DateTimeStringFormat)) // You are free to use any name. I used timestamp
            };

            var assumeRoleResponse = client.AssumeRole(assumeRoleRequest);

            if (assumeRoleResponse.HttpStatusCode == HttpStatusCode.OK)
            {
                return new AssumeRoleTokenDetail()
                {
                    AccessKeyId = assumeRoleResponse.Credentials.AccessKeyId,
                    AccessKeySecret = assumeRoleResponse.Credentials.SecretAccessKey,
                    SecurityToken = assumeRoleResponse.Credentials.SessionToken,
                    Expire = assumeRoleResponse.Credentials.Expiration
                };
            }`

I would love to do this without DLL dependency but i was not able to work that out. May be when I have some more time i will check the request using DLL and check what i am missing.

Hope this helps.

voronytskyi commented 4 years ago

Tnx! Now I getting different error: "The security token included in the request is invalid". Switching to amzn/selling-partner-api-models#730 now...

ericblade commented 4 years ago

Hi, In response to reported issues about access denied and IAM policy we are working to clarify this in our dev guide . Meanwhile If you are using IAM role while registering your application the policy should be attached to the IAM role and If you are using IAM user policy should be attached to the IAM user. If you are using IAM role in the application registration make sure you are using credentials along with STS token to make a request. Please refer here for more details: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html

@parvathm

I might note that the documentation presently goes through creating a role for the application, goes through creating the STS AssumeRole stuff, but makes absolutely no mention of having to call AssumeRole with that setup. It also makes no mention whatsoever that you can use a user as the ARN for the application.

This is objectively broken documentation.

charliecode commented 4 years ago

@ericblade Couldn't disagree with you more. This API is much more secure and therefore there's def a bit of a learning curve. That's frustrating, I get it. But to say the docs are "objectively broken" is a bit dramatic. The team at Amazon has shown a great willingness to listen to constructive recommendations from any developers working with this API. Based on those recommendations, they've made multiple changes over the last few months to the docs, some even major, in an effort to clarify things and help everyone out. They're doing their best during these crazy times, just like the rest of us are trying to do.

ericblade commented 4 years ago

This API is much more secure and therefore there's def a bit of a learning curve. That's frustrating, I get it. But to say the docs are "objectively broken" is a bit dramatic.

If the documentation for setting it up contradicts the documentation for how to use it, and are incompatible with each other -- how is that not broken? You cannot follow the setup instructions, and end up with a configuration that is compatible with the instructions on how to use it.

charliecode commented 4 years ago

@ericblade If you have a recommendation for how the docs could be made more clear in a certain section, and it makes sense, I think you'll find Amazon willing to make the change. It would help if you mentioned exactly where you think it needs changed and why it's confusing.

You said there's "absolutely no mention of having to call AssumeRole with that setup." But the direction is there. They're assuming you either already have experience with using AWS STS or at the very least are going to follow the two links they have in their docs where they explain how it works.

The first spot is here. Where it says - "The following steps explain how to create and configure IAM policies and entities with the end goal of creating an IAM role that you provide when you register your application. In this workflow you create an IAM user (with an AWS STS policy attached) that assumes an IAM role that has permissions to call Selling Partner API."

The second spot is here. Where it says - "Adding an AWS Security Token Service (AWS STS) policy to your IAM user enables you to request temporary AWS access keys that you can use to authenticate your requests to the Selling Partner API. These credentials expire after a set period of time, helping you to control access to your AWS resources."

Note the explanation as well as links to the AWS STS docs where you can learn how it works and find the "Actions" near the top left on the same page under which the "AssumeRole" is the first action stated.

ericblade commented 4 years ago

@charliecode ... and makes absolutely no mention of using STS anywhere in the documentation from that point forward. If you follow all of the documentation from "Connecting to the Selling Partner API", you will end up with a 403 Forbidden response to any query that looks like it should work, and be left scratching your head until you come up on one of the threads here. As the bulk of the traffic on this issues board seems to be, right now.

ericblade commented 4 years ago

request for specific clarifications in https://github.com/amzn/selling-partner-api-models/issues/786

girija45701 commented 4 years ago

X-Amz-Content-Sha256

Can someone tell me what this X-Amz-Sha265 value should be ? I tried passing hashed Empty string, but it is throwing error.

Searched through the web but got nothing. BTW I am not using Amazon SDK, only using Rest API library.

Any pointers would help. I tried to compare fiddler trace for both using AWS SDK and normal (my code using Rest Sharp). The difference is the X-Amz-Sha256 (Mine generating hash of empty string and the AWS SDK generating something. Below is the trace.

AWS SDK Trace:

POST https://sts.amazonaws.com/ HTTP/1.1
User-Agent: aws-sdk-dotnet-45/3.5.1.11 aws-sdk-dotnet-core/3.5.1.34 .NET_Runtime/4.0 .NET_Framework/4.0 OS/Microsoft_Windows_NT_6.2.9200.0 ClientSync
Content-Type: application/x-www-form-urlencoded; charset=utf-8
host: sts.amazonaws.com
X-Amz-Date: 20201124T175526Z
X-Amz-Content-SHA256: **c3351bb30nfk9847204c744657601d1f99eb436fclod378901co99becb4a1**
Authorization: AWS4-HMAC-SHA256 Credential=AKIA5SU6JNKNAKNXYIPQI6V/20201124/us-east-1/sts/aws4_request, SignedHeaders=content-type;host;user-agent;x-amz-content-sha256;x-amz-date, Signature=41d994f5dda0b7d6ncknsl92nknkcfs80616b688dcd06ae5d29113519165e3
Content-Length: 400
Connection: Keep-Alive

Action=AssumeRole&DurationSeconds=3600&Policy=%7B%22Version%22%3A%20%222012-10-17%22%2C%22Statement%22%3A%20%5B%7B%22Effect%22%3A%20%22Allow%22%2C%22Action%22%3A%20%22execute-api%3AInvoke%22%2C%22Resource%22%3A%20%22arn%3Aaws%3Aexecute-api%3A%2A%3A%2A%3A%2A%22%7D%5D%7D&RoleArn=arn%3Aaws%3Aiam%3A%3A933413647423%3Arole%2Fmarketplacesamplerole&RoleSessionName=TestGir-Role535292688&Version=2011-06-15

My code

POST https://sts.amazonaws.com/ HTTP/1.1
x-amz-content-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
X-Amz-Date: 20201124T175531Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIA5SU6NIKDQ797NK6V/20201124/us-east-1/sts/aws4_request, SignedHeaders=content-type;host;user-agent;x-amz-content-sha256;x-amz-date, Signature=ba3f5bcb25f0837ncisdk97nck824a40174391e011cf45e4584d9563f2adf044
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp/105.1.0.0
Content-Type: application/x-www-form-urlencoded
Host: sts.amazonaws.com
Content-Length: 400
Accept-Encoding: gzip, deflate

Action=AssumeRole&DurationSeconds=3600&Policy=%7B%22Version%22%3A%20%222012-10-17%22%2C%22Statement%22%3A%20%5B%7B%22Effect%22%3A%20%22Allow%22%2C%22Action%22%3A%20%22execute-api%3AInvoke%22%2C%22Resource%22%3A%20%22arn%3Aaws%3Aexecute-api%3A%2A%3A%2A%3A%2A%22%7D%5D%7D&RoleArn=arn%3Aaws%3Aiam%3A%3A933413647423%3Arole%2Fmarketplacesamplerole&RoleSessionName=TestGir-Role296485585&Version=2011-06-15
BeeBee234 commented 3 years ago

Howdy,

The C# code example in https://github.com/amzn/selling-partner-api-models/issues/31 uses RestSharp and works well for the following two sandbox calls if your credentials are setup properly:

    var resource = $"/orders/v0/orders";
    IRestRequest restRequest = new RestRequest(resource, Method.GET);
    restRequest.AddParameter("MarketplaceIds", "ATVPDKIKX0DER", ParameterType.QueryString);
    restRequest.AddParameter("CreatedAfter", "TEST_CASE_200", ParameterType.QueryString);

and

var resource = $"/vendor/orders/v1/purchaseOrders";
IRestRequest restRequest = new RestRequest(resource, Method.GET);
restRequest.AddParameter("createdAfter", "2019-08-20", ParameterType.QueryString);
restRequest.AddParameter("createdBefore", "2019-09-21", ParameterType.QueryString);

Have fun and good luck,

Brian

krybbio commented 3 years ago

hi, i'm tryng to use feeds-api but I get the

{
    "errors": [
        {
            "message": "Access to requested resource is denied.",
            "code": "Unauthorized",
            "details": ""
        }
    ]
}

No details!!!! I'm able to get access_token and the request is well signed here my headers:

sellingpartnerapi-eu.amazon.com
AWS4-HMAC-SHA256 Credential=XXXXXXX/20210104/eu-west-1/execute-api/aws4_request, SignedHeaders=host;user-agent;x-amz-access-token;x-amz-date, Signature=XXXX
XXX/1.0 (Language=PHP;Platform=Linux)
Atza|IwEBIE2faqgsU5Ezu56Fl4E1zee3KVTuRq27Jz1MUCFtkcVTa_0oiyBzv4c9igOhRUXdLlc4OY1RpoxQtAoAEd2jSyo9EaNq1Lv7Uf43QF1aoZ3_GJ_qM4nqDdEhNoibZW98VNtbjYtLeQRI046c61b6QKWouL-Qm5-o5uS6Oms4GbWU4JSTWaPDYv6XvRWCmlVim3QC18oRIE0zklnp-z1BLdBgMGi-Y3ilItU6ozngHJ9npM1hlNLW3ZWw2FzDw1E_o7t_sRByzc9kgXhzQjGghMBZOCGKUq62RYy_4KqePQm_5jjlI2BOdbWpsNNrZQ6iSnTB-oX3F1-fwHADXxHq7lVZ
20210104T193807Z

Did any one find a solutinon?

cdragon1116 commented 3 years ago

Still getting same errors after using assumeRole credentials

Confirmed that

I tried on the postman using AWS Signature Auth and still getting same error:

{
    "errors": [
        {
            "message": "Access to requested resource is denied.",
            "code": "Unauthorized",
            "details": ""
        }
    ]
}

Below is Curl Details:

curl --location --request GET 'https://sellingpartnerapi-na.amazon.com/orders/v0/orders?marketplace=ATVPDKIKX0DER' \
--header 'x-amz-access-token: Atza|IwEBIF5LclxTfQAJpR_KffJ2Bjsr4IKUcSJyv4L841q88J9rPbI75xWQW4jR_R_5vq7M_eZf2ROOmCCC2P2PJTk8FUBzePqXH2W56Nv97WtsxzNEi0G9EWl3zcCmA9H_f4j*****************E6Wy0Z03bU0VEHdXkhB-JasJcxzUaGxn9oPu7a6NRANTqgP5-g0FdZg5l2mPfbsIM6wHqo5-KF3m7eYb2FpcoSh1ct-GNUQUWu99qJai5-nNVHCiDk191tmBE9BfvviGujbTW_kw9Q4e_6WLYVF34DhFEO0vMFjjgv3PV6NezZoMharGikGEJwXHR5wpF' \
--header 'host: sellingpartnerapi-na.amazon.com' \
--header 'user-agent: LonglongTest' \
--header 'X-Amz-Security-Token: FwoGZXIvYXdzEAgaDCtrPmicPzRgIdDujSKqAcMtkqrd0AkluRH+4krLViSrg02Xm+U4Ge50uiqfmV/hE2v4tG1rOKvLyL0q8Pdf8NkETKK/YsgyqPTg06WCFh/jNd8e+ixD6S0*********************n6V+WyPwnnM3GDMuQsbDY8mxEbBDdKgc7YFk+lBWC0Ao979LVvbvhWCZRBDtr+inGVL+B2MSzWQpd+pS5SxB51hXpPjrKSw+MmgmUL7KK/j9v8FMi3bBSRS7xRpLcojibl0SUCi7SwR/wta8NYNDp+8QEw8KpkWoPAnsVi8eYsBpT8=' \
--header 'X-Amz-Date: 20210112T143330Z' \
--header 'Authorization: AWS4-HMAC-SHA256 Credential=ASIAUDJT3KUQK3H64W5J/20210112/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=a00f71736c10c15ef89a5b1d69576fd9e46f70bb2550e54c5bd075ea85df7932'

On the other hand, I'm trying to figure out the signed request for Ruby implementation, some how it's also not working.

client = Aws::STS::Client.new(:access_key_id => "AKIAUDJT3********", :secret_access_key => "mVJgiEiqB47wh7NbrW/*************", :region => "us-east-1")
resp = client.assume_role({
  role_arn: "arn:aws:iam::2819659*******:role/Admin",
  role_session_name: "sp-api",
})

signer = Aws::Sigv4::Signer.new(
  region: 'us-east-1',
  service: 'execute-api',
  credentials: resp.credentials
)

signature = signer.sign_request(
  http_method: 'GET',
  url: url,
  headers: {
    'host' => 'sellingpartnerapi-na.amazon.com',
    'user-agent' => 'Test (Language=Ruby)',
    'x-amz-access-token' => access_token
  },
  body: { MarketplaceIds: 'ATVPDKIKX0DER' }.to_json
)

response = HTTParty.send(
  :get, 
  'https://sellingpartnerapi-na.amazon.com/orders/v0/orders', 
  headers: {
    'host' => signature.headers['host'],
    'user-agent' => 'Test (Language=Ruby)',
    'x-amz-access-token' => access_token,
    'x-amz-content-sha256' => signature.headers['x-amz-content-sha256'],
    'x-amz-security-token' => resp.credentials['session_token'],
    'x-amz-date' => signature.headers['x-amz-date'],
    'Authorization' => signature.headers['authorization'],
  }, 
  body: { MarketplaceIds: 'ATVPDKIKX0DER' }.to_json
)

# response 
{"errors"=>[{"message"=>"Access to requested resource is denied.", "code"=>"Unauthorized", "details"=>"Access token is missing in the request header."}]}

Any help will be super appreciate!

krybbio commented 3 years ago

I believe there are steps missing from the selling-partner-api developer guide. The STS service should give you a full set of credentials. Then "Access key ID" and "Secret access key" should also be reset with the new credentials. But apparently the method to obtain the access token suggested by the guide does not report these credentials. I solved it by applying the policy directly to the user instead of the role. Then I set the App on seller central with the user's IAM ARN in order to bypass the STS service. It works perfectly!

cdragon1116 commented 3 years ago

@krybbio Would you help explain more?

Do you still need to do assumeRole and get the session_token after to apply policy directly to user? Just tried it still get the same error:

curl --location --request GET 'https://sellingpartnerapi-eu.amazon.com/orders/v0/orders?marketplace=A1F83G8C2ARO7P' \
--header 'x-amz-access-token: Atza|IwEBICq***************Xsj70Zu7Xxyxt7Vk_6o3GjsHUbBuD6uVHEWLn3k-hPIq0aUUNsD4mkWRPIJ6PWFmTMVqVrL9otiLomrUJKjcKeT6Ztk9XF3WlhAvdMBOcPk5v4_SbksDTcdiDGfB0SSW7-BJp_xYGWSYVgNPgI6ZSnCmYqCFMECaduagoCFfWGjp7GWL-dFiJNg2YxN6BsmoTM7WajAV4ljk6WmXR8SKD9OVGkmUfMlo83-q_N9BeNLG_i_******************hDj7LiCftddoi6JLXRHAVZLayGZjH_3cPCXPSVvTq8SW270qa6hi8wWWYpE8G_8KBDz_B4' \
--header 'X-Amz-Date: 20210113T115504Z' \
--header 'Authorization: AWS4-HMAC-SHA256 Credential=AKIAUDJT3KUQIRIKGDW6/20210113/eu-west-1/execute-api/aws4_request, SignedHeaders=host;x-amz-date, Signature=89ac7f52b58e516b9fa826b0d6015c9f0747c694b65503515fad05fdf76d0c53'
{
    "errors": [
        {
            "message": "Access to requested resource is denied.",
            "code": "Unauthorized",
            "details": ""
        }
    ]
}
krybbio commented 3 years ago

It looks like the guidance on the docs around adding a role doesnt seem to work (or I have messed it up somehow). The work around is to add the policy directly the user as per phamanh195 suggestion:

IAM Management Console => users => select user => add inline policy => click on JSON tab => add the following:

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:::*" } ] }

Appreciate it is not best practices, but i've got access now.

p.s. i have removed the policy and it has defaulted back to the authorization error above

Then you need to create a new App in seller central > App Store > Developer Central when configure it use User IAM ARN

cdragon1116 commented 3 years ago

@krybbio Super appreciate your help! You saved my day(I'm stuck on this for 3 days...) I finally got it work on Postman and cURL, now I'm trying to figure out the implementation. https://github.com/amzn/selling-partner-api-models/issues/945

johnkw commented 3 years ago

Can someone please clarify the status of this bug? An above comment said to contact support, but Seller Support is unresponsive for weeks on end. What is the way that it's supposed to work? Are we supposed to do the bizarre assumeRole stuff, or is it supposed to be possible to work without that?

ericblade commented 3 years ago

The main documentation received an update a few days ago saying that setting up with STS is recommended. The description of how to make a request has not been updated, however.

johnkw commented 3 years ago

Thanks - I do see commit 0fd032b159b430b0b8cc1148314df8fab7815deb which includes an off-hand mention of what appears to be an optional but recommended step, using STS. Is it actually a show-stopper critical step? Ie, you MUST use STS, not merely recommended?

I tried AssumeRole, and returns: AccessKeyId SecretAccessKey SessionToken. I then used those 3 to do a call, instead of the normal access, secret, and the token from api.amazon.com/auth/o2/token.

However, then I get the bug amzn/selling-partner-api-models#730 problem, and bug amzn/selling-partner-api-models#730 was closed with no resolution, so it's unclear what to do next. Any additional ideas?

I still don't understand if this use of STS is a crazy hack work-around, or is actually the intended normal way things are supposed to work. The documentation is still quite broken when it comes to that question.

johnkw commented 3 years ago

Thanks - I just got some calls to work! The additional trick was to simultaneously provide both "x-amz-access-token" via the normal login, and "x-amz-security-token" via the STS login. Very strange that it would require 2 different login methods at once. (I'm still not clear on whether this is all the proper expected way to do thing, or a crazy hack to work around some other bug that's not yet been clarified.)

ericblade commented 3 years ago

Glad to hear it's working. I've just recently got my code working for it, using STS, but it's super messy. I haven't really explored this API yet, just trying to do some homework on eventually switching over from MWS.

There is an open issue asking for clarification on the topic of using STS vs not using STS, but it looks like it's getting buried under all the newer issues.

https://github.com/amzn/selling-partner-api-models/issues/786

johnkw commented 3 years ago

Oh wow so I just switched over to the bug amzn/selling-partner-api-models#786 method. That is so much cleaner, simpler, and more logical. Just add the magic JSON thing to the user and the rest of the github documentation works at that point. No more seemingly pointless double-logins and extra x-amz-security-token field.

ericblade commented 3 years ago

It seems that's not the way they intend to do it, though. I'm not sure what the advantage of using STS is over that, but I'm going to stick with the recommendation now that I have it working

testniaccunt commented 3 years ago

I am getting the same error :) LWA gives a token back, i am signing the request, in my case it is "CreateFeedDocumentSpecification".

When i try to call sts.eu-west-1.amazonaws.com with the example from @girija45701 (AssumeRole.zip) ,i am getting a message:

When i try to call AmazonSecurityTokenServiceClient.AssumeRoleRequest i am getting: "WaitingForActivation"

I am unable to develop my softwer, i am confused, i followed the documentation, and this thread, all seems to be set properly. Can someone help me? Thx

SOLVED: i tried getting the token from LWS with refreshtoken, and it seems to be working

Now i have a problem when trying to upload a file (feed) in C# image

Encrypted is the feed, url is the url from step 1), i am recieving forbidden, signature. What should i do?

I am "testing" it on live endpoint (sellingpartnerapi-eu.amazon.com), because sandbox is giving me false data when calling "CreateFeedDocumentSpecification". Key and vector are not string64.

gavranovic672 commented 3 years ago

This code snippet in C# worked for me, i successfully uploaded a feed

My upload method:

private static bool UploadFile(byte[] encrypted, string url) { bool isUploaded = false;

var contentType = "text/tab-separated-values; charset=UTF-8";

var parameter = new Parameter
{
    Name = contentType,
    Value = encrypted,
    Type = ParameterType.RequestBody
};

var restRequest = new RestRequest(Method.PUT);
restRequest.Parameters.Add(parameter);

var restClient = new RestClient(url);
var response = restClient.Execute(restRequest);

isUploaded = response.StatusCode == System.Net.HttpStatusCode.OK;

return isUploaded;

}

seek78 commented 3 years ago

Hi, I'm facing this problem:

GET /?Version=2011-06-15&Action=AssumeRole&RoleSessionName=postmanSpApi&RoleArn=arn:aws:iam::94205*******:role/SellingPartner HTTP/1.1
Host: sts.amazonaws.com
X-Amz-Date: 20210204T225147Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIA5WVYBOR*********/20210204/eu-west-1/sts/aws4_request, SignedHeaders=host;x-amz-date, Signature=bf7e0b7dc32618efca7483a897ac52cc951aa65d23921f54429f69a04ef69816
User-Agent: PostmanRuntime/7.26.10
Accept: */*
Cache-Control: no-cache
Postman-Token: 4490bdf9-a00d-481a-b8f2-d930965f5703
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
HTTP/1.1 403 Forbidden
x-amzn-RequestId: 9c40525e-1952-4f21-8cc1-8c34069eae9c
Content-Type: text/xml
Content-Length: 317
Date: Thu, 04 Feb 2021 22:51:47 GMT
<ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
<Error>
<Type>Sender</Type>
<Code>SignatureDoesNotMatch</Code>
<Message>Credential should be scoped to a valid region, not 'eu-west-1'. </Message>
</Error>
<RequestId>9c40525e-1952-4f21-8cc1-8c34069eae9c</RequestId>
</ErrorResponse>

And I can't undertand what policy cause the problem. Trying with https://sellingpartnerapi-na.amazon.com/ endpoint result in

{
    "errors": [
        {
            "message": "Access to requested resource is denied.",
            "code": "Unauthorized",
            "details": ""
        }
    ]
}

I want to use European endpoint, someone can give me a hint? Tnx

cdragon1116 commented 3 years ago

@seek78 I see you are using different region & endpoint

The combination should be

SP_API_DOMAIN = {
        'us-east-1' => "sellingpartnerapi-na.amazon.com", 
        'eu-west-1' => "sellingpartnerapi-eu.amazon.com", 
        'us-west-2' => "sellingpartnerapi-fe.amazon.com", 
}

If you link a different seller account to your application with different region. It won't work. Try to test on the account that you create that application

seek78 commented 3 years ago

@seek78 I see you are using different region & endpoint

The combination should be

SP_API_DOMAIN = {
        'us-east-1' => "sellingpartnerapi-na.amazon.com", 
        'eu-west-1' => "sellingpartnerapi-eu.amazon.com", 
        'us-west-2' => "sellingpartnerapi-fe.amazon.com", 
}

If you link a different seller account to your application with different region. It won't work. Try to test on the account that you create that application

Hi @cdragon1116 and thanks. I know: my account was created in Italy, I use sellingpartnerapi-eu.amazon.com to succesfully get the token, but "asking" for orders it bounce me. Maybe the problem is the accout? Maybe the IAM policy?

cdragon1116 commented 3 years ago

Make sure you attached all the policies in your IAM user & role which follows Seller Parter Doc

After that, you should sign your request with the assumeRole credentials generate by your IAM role ARN (access_key_id, secret_access_key, session_token)

More details of your Order Request will be helpful to debug

seek78 commented 3 years ago

Make sure you attached all the policies in your IAM user & role which follows Seller Parter Doc

After that, you should sign your request with the assumeRole credentials generate by your IAM role ARN (access_key_id, secret_access_key, session_token)

More details of your Order Request will be helpful to debug

I followed exactly that guide for config. Here the log of the 2 calls: 1st get token, 2nd get orders

POST https://api.amazon.com/auth/o2/token
200
3.54 s
POST /auth/o2/token HTTP/1.1
User-Agent: PostmanRuntime/7.26.10
Accept: */*
Cache-Control: no-cache
Postman-Token: 4207526f-e968-4b33-b780-89d1b3d654ad
Host: api.amazon.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 524
grant_type=refresh_token&refresh_token=Atzr%7CIwEBIGGhWe8o87-aP9gf**************rIPz282ABsRfZCadFToT641w91l_8I0UqcBIoR5j-nEfNfdOnh5hFJuav9FhvvVNed21RZaVF9YnWEnCI6jaBeG8b7RkP9XUtHaS-vg6U0Y-W8hma-YmrnvxK3Qot71UEC9vTDweUMi7_lEn7JuXc6bjEpdUbjv6LHK6iEJlTK_P0NXA_zViNHP60uZ5okAAECt5rgTuUHh3Yndjb99SgFaMclFamt7okp9LDcqq-MHXGqaZUCXz9Ycpmzootb4hHgxWDNZrwjOeerSmMDUzZ1f4Npc&client_id=amzn1.application-oa2-client.6eca0c618e57416cb6e67c59c24786ea&client_secret=f618c8e19712797e3fdb1cca1ddde1c4e1968c55276df3a16afc370b95e70a41
HTTP/1.1 200 OK
Server: Server
Date: Fri, 05 Feb 2021 08:58:35 GMT
Content-Type: application/json;charset=UTF-8
Content-Length: 763
Connection: keep-alive
x-amz-rid: 6W6P0WY8HYT5WQ7PNENF
x-amzn-RequestId: 53c696ac-f181-40cb-8040-7c1a23c65ba6
X-Amz-Date: Fri, 05 Feb 2021 08:58:35 GMT
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Vary: Content-Type,Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent
{"access_token":"Atza|IwEBIOO5bP3zisEeDMtP-HO9C9iVEqH-jz_j6ilu9****************JnyzJW0JPbsGkdD7Ld1m5i9f7r7VeFbwkg7euYfaCNsPOcA0NR8YmVzTyRzkTsU63niBZcruPpsBsZlgYqJGikPV2gi9BSoBE7LpCO45EjPipvEi1AhcJmpDboYIf2Jr8X9931lo5GzsYWDZkMTu9L7BlASYl59Fxo7pGvR-VmASWH2MPt9I72AQJEl8XQhxiZdrtB69jbNT65QKhk2qnmQep4nRurTglTfQFqVdEapvuFO_AHnE3hoHAWKJhVRIkcIvdRk_9rH1kOoeAKMLQ0WLq6PS","refresh_token":"Atzr|IwEBIGGhWe8o87-aP9gfCqSKBGsoJJintDF-gNCCgfNorIPz282ABsRfZCadFToT641w91l_8I0UqcBIoR5j-nEfNfdOnh5hFJuav9FhvvVNed21RZaVF9YnWEnCI6jaBeG8b7RkP9XUtHaS-vg6U0Y-W8hma-YmrnvxK3Qot71UEC9vTDweUMi7_lEn7JuXc6bjEpdUbjv6LHK6iEJlTK_P0NXA_zViNHP60uZ5okAAECt5rgTuUHh3Yndjb99SgFaMclFamt7okp9LDcqq-MHXGqaZUCXz9Ycpmzootb4hHgxWDNZrwjOeerSmMDUzZ1f4Npc","token_type":"bearer","expires_in":3600}

GET https://sts.amazonaws.com/?Version=2011-06-15&Action=AssumeRole&RoleSessionName=postmanSpApi&RoleArn=arn:aws:iam::******50939:role/SellingPartner
403
685 ms
GET /?Version=2011-06-15&Action=AssumeRole&RoleSessionName=postmanSpApi&RoleArn=arn:aws:iam::******50939:role/SellingPartner HTTP/1.1
Host: sts.amazonaws.com
X-Amz-Date: 20210205T085835Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIA5WVYBO********/20210205/eu-west-1/sts/aws4_request, SignedHeaders=host;x-amz-date, Signature=998b28feba1b2377f6068dddb59cf0f3fc1d9166906e18569cfe3d38ae338831
User-Agent: PostmanRuntime/7.26.10
Accept: */*
Cache-Control: no-cache
Postman-Token: d4b174cf-dfd1-4afe-8af9-e755e80500b9
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
HTTP/1.1 403 Forbidden
x-amzn-RequestId: b958b0e2-3b9c-42a5-b2a5-b8e8f812c06e
Content-Type: text/xml
Content-Length: 317
Date: Fri, 05 Feb 2021 08:58:35 GMT
<ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
<Error>
<Type>Sender</Type>
<Code>SignatureDoesNotMatch</Code>
<Message>Credential should be scoped to a valid region, not 'eu-west-1'. </Message>
</Error>
<RequestId>b958b0e2-3b9c-42a5-b2a5-b8e8f812c06e</RequestId>
</ErrorResponse>
q8ferd commented 3 years ago

Hello, l've this error code ""message": "Invalid Signature.",

I'm using c#. Here is my piece of code.

    public class SellerAPICredentials
    {
        public string ClientId = "amzn1.application-oa2-clientxxxxxxxxxxxx";
        public string ClientSecret = "xxxxxxxxxxxxxxxxx";
        public string RefreshToken = "Atzr|xxxxxxxxxx";
        public string AWSKey = "AKIAxxxxxxxxxxxxxx";
        public string AWSSecret = "xxxxxxxxxxxxxxxxx";
        public string RoleARN = "arn:aws:iam::xxxxxxxxxx:role/RuoloTest";
    }

    static void OrderImport()
    {
        var resource = $"/orders/v0/orders";

        IRestRequest restRequest = new RestRequest(resource, Method.GET);
        var client = new RestClient("https://sellingpartnerapi-eu.amazon.com");
        var credentials = new SellerAPICredentials();

        restRequest = SignWithAccessToken(restRequest, credentials.ClientId, credentials.ClientSecret, credentials.RefreshToken);
        restRequest = SignWithSTSKeysAndSecurityTokenn(restRequest, client.BaseUrl.Host, credentials.RoleARN, credentials.AWSKey, credentials.AWSSecret);

        restRequest.AddParameter("MarketPlaceIds", "APJ6JRA9NG5V4", ParameterType.QueryString);
        restRequest.AddParameter("createdAfter", DateTime.UtcNow.AddDays(-5).ToString("yyyy-MM-dd"), ParameterType.QueryString);
        restRequest.AddParameter("createdBefore", DateTime.UtcNow.ToString("yyyy-MM-dd"), ParameterType.QueryString);
        restRequest.AddHeader("user-agent", "RestSharp/106.11.7.0");

        var result = client.Execute(restRequest);

    }

    private static IRestRequest SignWithAccessToken(IRestRequest restRequest, string clientId, string clientSecret, string refreshToken)
    {
        var lwaAuthorizationCredentials = new LWAAuthorizationCredentials
        {
            ClientId = clientId,
            ClientSecret = clientSecret,
            Endpoint = new Uri("https://api.amazon.com/auth/o2/token"),
            RefreshToken = refreshToken,
        };

        return new LWAAuthorizationSigner(lwaAuthorizationCredentials).Sign(restRequest);
    }
    private static IRestRequest SignWithSTSKeysAndSecurityTokenn(IRestRequest restRequest, string host, string roleARN, string accessKey, string secretKey)
    {
        AssumeRoleResponse response1 = null;
        using (var STSClient = new AmazonSecurityTokenServiceClient(accessKey, secretKey, RegionEndpoint.EUWest1))
        {
            var req = new AssumeRoleRequest()
            {
                RoleArn = roleARN,
                DurationSeconds = 950, //put anything you want here
                RoleSessionName = Guid.NewGuid().ToString()
            };

            response1 = STSClient.AssumeRoleAsync(req, new CancellationToken()).Result;
        }

        //auth step 3
        var awsAuthenticationCredentials = new AWSAuthenticationCredentials
        {
            AccessKeyId =  response1.Credentials.AccessKeyId,
            SecretKey =  response1.Credentials.SecretAccessKey,
            Region = "eu-west-1"
        };

     restRequest.AddHeader("x-amz-security-token", response1.Credentials.SessionToken);

        return new Amazon.SellingPartnerAPIAA.AWSSigV4Signer(awsAuthenticationCredentials)
                        .Sign(restRequest, host);
    }

Am i missing something? I'm calling assume role funcion and using his repsonse parameters to sign my request.


I've also tried with python with the same credetials and error is "Access to requested resource is denied." I'm lost.

Can anyone help me? Thanks in advance

avvarga commented 3 years ago

Hello all,

Thank you for the feedback provided in this and other issues open regarding the status of STS in our documentation.

I have reached out to our writers in order to update the documentation and clarify certain aspects of this Authentication method, which will continue to be tracked in #128.

In regards to the original reason for this issue being opened, which are "Access Denied" errors, please know that the nature of these errors require that we handle them on a case per case basis and via a support case (which can be opened here) as in the majority of these cases specific details about the account or the call itself may be requested and cannot be available publicly.

I am closing this issue since the original post is not regarding the documentation or this repository and this issue keeps getting bigger regarding different scenarios with "Access Denied", "Signature missmatch" and other different errors that are not bugs or document improvements.

Thank you again for your feedback!

kevinhq commented 3 years ago

Hi,

We have same issue and we've tried everything on this thread but none work.

So, we open new case on Amazon but Amazon replied:

We have closed this case because Amazon has deactivated your account. Refer to your Account Health Dashboard to learn more about the status of your account. ...

Yes, our seller account is not active. But our MWS account is active and we can use MWS API.

My question is: do we need active seller account for accessing Amazon Selling Partner API? Isn't the MWS account enough? Or am I missing something here?

moltar commented 3 years ago

Same problem here!

Case ID 8166141741

https://github.com/amzn/selling-partner-api-models/issues/1179

pawan1793 commented 3 years ago

It looks like the guidance on the docs around adding a role doesnt seem to work (or I have messed it up somehow). The work around is to add the policy directly the user as per phamanh195 suggestion:

IAM Management Console => users => select user => add inline policy => click on JSON tab => add the following:

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:::*" } ] }

Appreciate it is not best practices, but i've got access now.

p.s. i have removed the policy and it has defaulted back to the authorization error above/ hey @krybbio @cdragon1116 I tried same thing ... but it's not working ..... Do I have to create new app again after updating policy ? Stuck on this for days ...

krybbio commented 3 years ago

It looks like the guidance on the docs around adding a role doesnt seem to work (or I have messed it up somehow). The work around is to add the policy directly the user as per phamanh195 suggestion: IAM Management Console => users => select user => add inline policy => click on JSON tab => add the following: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:::*" } ] } Appreciate it is not best practices, but i've got access now. p.s. i have removed the policy and it has defaulted back to the authorization error above/ hey @krybbio @cdragon1116 I tried same thing ... but it's not working ..... Do I have to create new app again after updating policy ? Stuck on this for days ...

Yes, you must create a new App in seller central > App Store > Developer Central when configure it use User IAM ARN

kevinhq commented 3 years ago

Same problem here!

Case ID 8166141741

amzn/selling-partner-api-models#1179

Any update from them? I assume you have active seller account since you can open a case with them?