amz_sp_api icon indicating copy to clipboard operation
amz_sp_api copied to clipboard

Access to requested resource is denied?

Open kevinhq opened this issue 4 years ago • 17 comments

Log:

ETHON: Libcurl initialized
ETHON: performed EASY effective_url=https://api.amazon.com/auth/o2/token response_code=200 return_code=ok total_time=1.40582
ETHON: performed EASY effective_url=https://sellingpartnerapi-na.amazon.com/authorization/v1/authorizationCode?sellingPartnerId=***&developerId=***&mwsAuthToken=amzn.mws.*** response_code=403 return_code=ok total_time=1.632658
AmzSpApi::ApiError: Error message: the server returns an error
HTTP status code: 403
Response headers: {"Date"=>"Fri, 12 Mar 2021 07:20:49 GMT", "Content-Type"=>"application/json", "Content-Length"=>"141", "Connection"=>"keep-alive", "x-amzn-RequestId"=>"cdde3360-8e04-4f1d-8f8e-57eea04d196c", "x-amzn-ErrorType"=>"AccessDeniedException", "x-amz-apigw-id"=>"cEBsrH3EoAMFfKg="}
Response body: {
  "errors": [
    {
      "message": "Access to requested resource is denied.",
     "code": "Unauthorized",
     "details": ""
    }
  ]
}

It seems we have the same problem here

We've followed the suggestion there, but it doesn't work for us.

Then, one of Amazon support said this:

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

My question is, is this gem sending that STS token to make a request? I haven't explored the codes base too deep but if you can give any hint, I'll appreciate it.

Thanks for building this.

kevinhq avatar Mar 12 '21 07:03 kevinhq

@kevinhq I haven't personally tested it, but I added documentation for how to pass a credentials_provider (of which STS is one) through to the signer in the readme on https://github.com/ericcj/amz_sp_api Please close this issue if it works

ericcj avatar Mar 23 '21 18:03 ericcj

@ericcj - We tried that documentation, such as:

 require 'aws-sdk-core'
  config.credentials_provider = Aws::STS::Client.new(
    region: AmzSpApi::SpConfiguration::AWS_REGION_MAP['na'],
    access_key_id: ENV['AMZ_SP_API_ACCESS_KEY'],
    secret_access_key: ENV['AMZ_SP_API_SECRET_KEY']
  ).assume_role(role_arn: '*****', role_session_name: SecureRandom.uuid)

But, we got same error. We've gone through the AWS SP-API doc several times and we're sure to follow each of them literally.

Now, I wonder if SP-API needs Seller account to be active since ours isn't active (but MWS account is)

kevinhq avatar Mar 30 '21 13:03 kevinhq

that looks correct to me. since it doesn't crash and we're passing credentials_provider directly to their signing gem i don't think it's a bug with our client (you could double-check the requests/headers look sane with config.debugging = true). but please let us know if you can resolve it with them.

ericcj avatar Mar 31 '21 17:03 ericcj

Just tried with config.debugging = true. Here are the relevant log ( I think ):

Calling API: AuthorizationApi.get_authorization_code ...
Libcurl initialized
...
effective_url=https://api.amazon.com/auth/o2/token response_code=200 return_code=ok total_time=2.760831
...
effective_url=https://sellingpartnerapi-na.amazon.com/authorization/v1/authorizationCode?sellingPartnerId=***&developerId=***&mwsAuthToken=amzn.mws.*** response_code=403 return_code=ok total_time=1.638323

here's how I call it on rails console:

api_instance = AmzSpApi::AuthorizationApiModel::AuthorizationApi.new(AmzSpApi::SpApiClient.new)
result = api_instance.get_authorization_code(selling_partner_id, developer_id, mws_auth_token)

Am I missing something here?

kevinhq avatar Apr 17 '21 13:04 kevinhq

are you trying to migrate an MWS authorization to the SP-API or do you already have the SP-API refresh_token directly? the fact that the initial access token request (https://github.com/ericcj/amz_sp_api/blob/main/lib/sp_api_client.rb#L35) is succeeding suggests you already have the refresh_token set in config and don't need to call get_authorization_code, which is for the use case of migrating MWS credentials when you don't want to ask the seller to authorize your SP-API app: https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/use-case-guides/authorization-api-use-case-guide

That use case of migrating MWS authorization (or any "Grantless operation" for that matter) isn't supported by this gem yet and I'm not 100% clear on how to support it but would welcome a patch. if that's what you want to do, it sounds like you'd make the get_authorization_code request either totally outside the context of this gem or just by not passing SpApiClient to it (since it doesn't require any authorization or signing) to get the refresh_token that you'd then set into this gem's configuration to go about making SP-API requests. but i'm a little confused about the final step of that tutorial of how you exchange the authorization code for the refresh_token and where you pass withScopes SCOPE_MIGRATION_API, since I also haven't used the oauth flows myself. i've only been using self-authorization so far.

ericcj avatar Apr 20 '21 14:04 ericcj

Hi, we also use self-authorization. Yes, we:

  • try to migrate from MWS auth to the SP-API, and
  • we already have the refresh_token set in config.

The problem is, other SP-API end point like reports return the same error too.

Tried with npm package for SP API as well (link), and get exactly same error for any end point.

It looks like we really need an active Seller Account as suggested by other folks.

kevinhq avatar Apr 21 '21 09:04 kevinhq

Hi all, I'm getting the exact same thing.. and I'm trying to go thru the sandbox which isn't helping anything. All I've done is set: config.sandbox = true which I think is right? Not sure..

but any movement on this issue @kevinhq

Trimakas avatar May 12 '21 17:05 Trimakas

@Trimakas - not yet. The product owner decides to setup seller account, and it's still on progress.

kevinhq avatar May 13 '21 09:05 kevinhq

Hi everyone,

I am trying to integrate with Amazon seller for the first time (not migrating from MWS) I have the same issue "access denied".
There is one comment in selling-partner-api-docs which people refer to as helpful, but I have no idea how to use it.. https://github.com/amzn/selling-partner-api-docs/issues/24#issuecomment-712216125

Can it be the solution for ruby as well? if so, how can it be used? Thank you!

estafaa avatar Jun 22 '21 02:06 estafaa

@estafaa would need to see your log/example usage. there's no known issue if you're providing a valid sp-api refresh_token

ericcj avatar Jun 25 '21 16:06 ericcj

@estafaa would need to see your log/example usage. there's no known issue if you're providing a valid sp-api refresh_token

I have a seller account on Amazon, an approved developer, and followed instructions on creating users on AWS. here is the action:

        require 'amz_sp_api'
        require 'fulfillment-outbound-api-model'

          AmzSpApi.configure do |config|
            config.refresh_token = "Atzr|IwEBIEGX0TyNtQvXAVP4JY8ovHZ6miTTuxbvm326VJipESotn2o1RvB8YUj30NAcwl7NUSP4Yd7DOGmvOKYJrloCEVE3PyX-yAAcW7LPzULtryfwO7N24p3uFPLAm......................"
            config.client_id = "amzn1.application-oa2-client.d2a9747.........................."
            config.client_secret = "ff1faae4ccc3206b788cb444165e91a2c1.................................."
        
            config.aws_access_key_id = "AKIA3EZPV4.................."
            config.aws_secret_access_key = "m8hkjyzbkaRmShV3bgI.................."
       
        
            config.region = 'na'
            config.timeout = 20 # seconds
            #  config.debugging = true
        
            
            config.save_access_token = -> (access_token_key, token) do
              Rails.cache.write("SPAPI-TOKEN-#{access_token_key}", token[:access_token], expires_in: token[:expires_in] - 60)
            end
            config.get_access_token = -> (access_token_key) { Rails.cache.read("SPAPI-TOKEN-#{access_token_key}") }
          end
  
  
        
        begin
          api = AmzSpApi::FulfillmentOutboundApiModel::FbaOutboundApi.new(AmzSpApi::SpApiClient.new) 
          p api.list_all_fulfillment_orders.payload
          
         # p api.get_fulfillment_order("S01-0529021-0503651")
        rescue AmzSpApi::ApiError => e
          puts "Exception when calling SP-API: #{e}"
        end

and response:


ETHON: Libcurl initialized
source=rack-timeout id=c2e1cde9-59e3-49b7-b147-799b2a204793 timeout=15000ms service=1007ms state=active
ETHON: performed EASY effective_url=https://api.amazon.com/auth/o2/token response_code=200 return_code=ok total_time=0.065271
ETHON: performed EASY effective_url=https://sellingpartnerapi-na.amazon.com/fba/outbound/2020-07-01/fulfillmentOrders response_code=403 return_code=ok total_time=0.058971
Exception when calling SP-API: Error message: the server returns an error
HTTP status code: 403
Response headers: {"Date"=>"Sun, 27 Jun 2021 22:28:36 GMT", "Content-Type"=>"application/json", "Content-Length"=>"141", "Connection"=>"keep-alive", "x-amzn-RequestId"=>"56bd03bd-9f6f-4013-8623-68f09bf0720e", "x-amzn-ErrorType"=>"AccessDeniedException", "x-amz-apigw-id"=>"Bmw_SFo3oAMF-6A="}
Response body: {
  "errors": [
    {
      "message": "Access to requested resource is denied.",
     "code": "Unauthorized",
     "details": ""
    }
  ]
}

Thank you!

estafaa avatar Jun 27 '21 22:06 estafaa

@estafaa your usage is correct, and the token request succeeds so your refresh_token/client_id/secret must be correct, but the aws_access_key must not be correctly associated so you'll have to contact amazon support it doesn't appear to be an issue with this gem

ericcj avatar Jun 29 '21 15:06 ericcj

@ericcj I am trying to create an app with SP API but I am facing the same issue `

  AmzSpApi.configure do |config|
    config.refresh_token = "token from seller dashboard app"
    config.client_id = "client id of seller app"
    config.client_secret = "secret of sller app"
    
    config.aws_access_key_id = "access key of new user create with required role"
    config.aws_secret_access_key = "secret key of new user create with required role"

    config.region = 'eu'
    config.timeout = 20 # seconds
    config.save_access_token = -> (access_token_key, token) do
      Rails.cache.write("SPAPI-TOKEN-#{access_token_key}", token[:access_token], expires_in: token[:expires_in] - 60)
    end
    config.get_access_token = -> (access_token_key) { Rails.cache.read("SPAPI-TOKEN-#{access_token_key}") }
  end

` I tried deleting and creating user multiple time But I am still getting error

`2.4.1 :003 > p api.list_all_fulfillment_orders.payload
ETHON: performed EASY effective_url=https://api.amazon.com/auth/o2/token response_code=200 return_code=ok total_time=1.413033
ETHON: performed EASY effective_url=https://sellingpartnerapi-eu.amazon.com/fba/outbound/2020-07-01/fulfillmentOrders response_code=403 return_code=ok total_time=0.827445
AmzSpApi::ApiError: Error message: the server returns an error
HTTP status code: 403
Response headers: {"date"=>"Mon, 23 Aug 2021 20:05:44 GMT", "content-type"=>"application/json", "content-length"=>"141", "x-amzn-requestid"=>"97055968-6d9a-4bea-8204-4a9b9fae46e0", "x-amzn-errortype"=>"AccessDeniedException", "x-amz-apigw-id"=>"EiTfzE9rjoEFQgA="}
Response body: {
  "errors": [
    {
      "message": "Access to requested resource is denied.",
     "code": "Unauthorized",
     "details": ""
    }
  ]
}

I have read lots of docs and have updated the users and role setting correctly

ayazahmadtarar avatar Aug 23 '21 20:08 ayazahmadtarar

@estafaa any update on above issue? I have cross-checked every credential and the whole flow seems okay but still getting error

ayazahmadtarar avatar Sep 07 '21 19:09 ayazahmadtarar

@estafaa any update on above issue? I have cross-checked every credential and the whole flow seems okay but still getting error

That time I contacted Amazon support and they told me that it probably does not work because on my seller account I have a negative $ balance. That time I stopped developing in that direction because we almost always have a negative balance on our amazon seller account because we use Amazon only for MFC (they ship our products), each time we ask them to ship, our balance goes more minus and then we pay Amazon, balance becomes 0, etc. Do you also have a negative balance? (just in case, you can see your balance at sellercenthttps://sellercentral.amazon.com/home )

estafaa avatar Sep 07 '21 22:09 estafaa

If anyone needs a quick solutions to allow for grantless operations (i needed it for notifications) i made this gist

You can then create some credentials like this:

credentials = AmzSpApi::SpConfiguration.new
credentials.client_id = 
credentials.client_secret = 
credentials.aws_access_key_id = 
credentials.aws_secret_access_key =
credentials.region = 
credentials.refresh_token = 

// You should only add these when doing a grantless operation
credentials.scope = 'sellingpartnerapi::notifications'
credentials.grant_type = 'client_credentials'

To make a Grant-less call

iamricks avatar Jan 11 '22 15:01 iamricks

@estafaa your usage is correct, and the token request succeeds so your refresh_token/client_id/secret must be correct, but the aws_access_key must not be correctly associated so you'll have to contact amazon support it doesn't appear to be an issue with this gem

It is interesting what you say here. We are getting 403 access denied for everything apart from MWS auth token exchange and LWA token exchange.

Nowhere in the SP-API docs that I can see does it say WHICH AWS credentials we are supposed to use! I am starting to think we are using the wrong ones. Can anyone shed light on that?

philsmy avatar Aug 08 '22 13:08 philsmy