Service: AmazonSQS; Status Code: 403; Error Code: AccessDenied

Hi,

I have some issues using aws-java-sdk to connect/fetch to my AWS account.

From the command line I can list all queues from my "profile" like:

Service: AmazonSQS; Status Code: 403; Error Code: AccessDenied

When I like to do the same thing in Java I get an exception: com.amazonaws.services.sqs.model.AmazonSQSException: Access to the resource https://sqs.eu-west-1.amazonaws.com/ is denied. (Service: AmazonSQS; Status Code: 403; Error Code: AccessDenied; Request ID: 90ae2bd8-eb2e-53e7-a44b-729e9cbb2e5a)

The code is simple:

ProfileCredentialsProvider prof = new ProfileCredentialsProvider("dev"); AmazonSQS sqs = AmazonSQSClientBuilder.standard() .withRegion("eu-west-1") .withCredentials(new AWSStaticCredentialsProvider(prof.getCredentials())) .build(); ListQueuesResult res = sqs.listQueues(); for (String url : res.getQueueUrls()) { System.out.println(url); }

The same result I get if I set up BasicAWSCredentials with my keys.

what I'm doing wrong?!

BR

我目前在尝试使用Spring Cloud和Spring Boot连接到AWS SQS队列时遇到连接问题。 我相信我一切都配置良好,但得到了:

2015-07-01 18:12:11,926 [WARN][-]
org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext[487]
- Exception encountered during context initialization - cancelling refresh attempt
org.springframework.context.ApplicationContextException: Failed to
start bean 'simpleMessageListenerContainer'; nested exception is
com.amazonaws.AmazonServiceException: Access to the resource
https://sqs.us-west-2.amazonaws.com/{Number}/{Queue Name} is denied.
(Service: AmazonSQS; Status Code: 403; Error Code: AccessDenied;
Request ID: 87312428-ec0f-5990-9f69-6a269a041b4d)

1
2
3
4
5
6
7
8
9
10

@Configuration
@EnableSqs
public class CloudConfiguration {
    private static final Logger log = Logger.getLogger(CloudConfiguration.class);

    @MessageMapping("QUEUE")
    public void retrieveProvisionMessages(User user) {
        log.warn(user.firstName);
    }
}

YML

1
2
3
4
5
6

cloud:
    aws:
       credentials.accessKey: AccessKey
       credentials.secretKey: SecretKey
       region.static: us-west-2
       credentials.instanceProfile: true

当它尝试连接时,我看到标头值为:

1

AWS4-HMAC-SHA256 Credential=accesskey/20150701/us-west-2/sqs/aws4_request, SignedHeaders=host;user-agent;x-amz-date, Signature=signature

发送请求后:

1

HTTP/1.1 403 Forbidden [Server: Server, Date: Wed, 01 Jul 2015 22:51:25 GMT, Content-Type: text/xml, Content-Length: 349, Connection: keep-alive, x-amzn-RequestId: Request Id] org.apache.http.conn.BasicManagedEntity@37e55df6

我已经检查了所有AIM政策,它们是正确的。

使用:

1
2
3
4
5
6
7
8
9

private AmazonSQS establishQueue(){
    AmazonSQS sqs = new AmazonSQSClient(new BasicAWSCredentials(accessKey, secretKey));
    sqs.setRegion(RegionUtils.getRegion(region));
    return sqs;
}

    AmazonSQS sqs = establishQueue();
    return sqs.receiveMessage(sqs.getQueueUrl(userProductPurchase).getQueueUrl());

使用相同的凭据可以正常工作。 任何帮助是极大的赞赏。

谢谢


您的IAM用户是否允许GetQueueAttributes呼叫?

我认为它也使用了很少的其他操作。 不仅ReceiveMessage和GetQueueUrl。


就我而言,使用Spring Cloud,我必须设置以下权限:

  • sqs:DeleteMessage
  • sqs:GetQueueUrl
  • sqs:ReceiveMessage
  • sqs:SendMessage
  • sqs:GetQueueAttributes

7 Answers

NewestMost votesMost comments

Hi,
Not sure if this is the problem, but here is my first guess..
If you currently have something like this:

const sQS = new SQSClient({ profile: 'default', region: 'region' });

You will need to change to this so that the application will pickup the credentials from the role instead of from the default profile:

const sQS = new SQSClient({ region: 'region' });

-randy

Hi RandyTakeshita,

Thank you very much for the response, yes we using same what you have suggested.

AmazonSQSClient client = new AmazonSQSClient('RegionEndpoint.APNortheast2');

Hi,
Can you please add the complete Access Denied message, along with the Roles/Policies/Trust Relationships currently used for SQS.
Thanks,
-randy

Sure,

Error:
Amazon.SQS.AmazonSQSException: The security token included in the request is invalid. ---> Amazon.Runtime.Internal.HttpErrorResponseException: The remote server returned an error: (403) Forbidden. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden. at System.Net.HttpWebRequest.GetResponse() at Amazon.Runtime.Internal.HttpRequest.GetResponse() --- End of inner exception stack trace --- at Amazon.Runtime.Internal.HttpRequest.GetResponse() at Amazon.Runtime.Internal.HttpHandler1.InvokeSync(IExecutionContext executionContext) at Amazon.Runtime.Internal.Unmarshaller.InvokeSync(IExecutionContext executionContext) at Amazon.SQS.Internal.ValidationResponseHandler.InvokeSync(IExecutionContext executionContext) in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Services\SQS\Custom\Internal\ValidationResponseHandler.cs:line 29 at Amazon.Runtime.Internal.ErrorHandler.InvokeSync(IExecutionContext executionContext) --- End of inner exception stack trace --- at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) at Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext executionContext, Exception exception) at Amazon.Runtime.Internal.ErrorHandler.InvokeSync(IExecutionContext executionContext) at Amazon.Runtime.Internal.CallbackHandler.InvokeSync(IExecutionContext executionContext) at Amazon.Runtime.Internal.RetryHandler.InvokeSync(IExecutionContext executionContext) at Amazon.Runtime.Internal.CallbackHandler.InvokeSync(IExecutionContext executionContext) at Amazon.Runtime.Internal.CallbackHandler.InvokeSync(IExecutionContext executionContext) at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeSync(IExecutionContext executionContext) at Amazon.Runtime.Internal.MetricsHandler.InvokeSync(IExecutionContext executionContext) at Amazon.Runtime.Internal.RuntimePipeline.InvokeSync(IExecutionContext executionContext) at Amazon.Runtime.AmazonServiceClient.Invoke\[TRequest,TResponse](TRequest request, IMarshaller2 marshaller, ResponseUnmarshaller unmarshaller) at Amazon.SQS.AmazonSQSClient.ReceiveMessage(ReceiveMessageRequest request) in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Services\SQS\Generated_bcl45\AmazonSQSClient.cs:line 2371

Policy:
We gave full sqs access to policy we had linked on our aws ec2.

Hi,
My next guess is that you have credentials already defined on the EC2 instance (that do NOT have full permissions) that is taking precedence over the full permissions policy that has been given to EC2 (based on the Credential Provider Chain described below). Note roles/policy given to EC2 are the lowest precedence in the chain, so go through each of the steps below to see if something else is taking precedence.
https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html

When you initialize a new service client without supplying any arguments, the AWS SDK for Java attempts to find AWS credentials by using the default credential provider chain implemented by the DefaultAWSCredentialsProviderChain class. The default credential provider chain looks for credentials in this order: Environment variables–AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. The AWS SDK for Java uses the EnvironmentVariableCredentialsProvider class to load these credentials. Java system properties–aws.accessKeyId and aws.secretKey. The AWS SDK for Java uses the SystemPropertiesCredentialsProvider to load these credentials. The default credential profiles file– typically located at ~/.aws/credentials (location can vary per platform), and shared by many of the AWS SDKs and by the AWS CLI. The AWS SDK for Java uses the ProfileCredentialsProvider to load these credentials. You can create a credentials file by using the aws configure command provided by the AWS CLI, or you can create it by editing the file with a text editor. For information about the credentials file format, see AWS Credentials File Format. Amazon ECS container credentials– loaded from the Amazon ECS if the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set. The AWS SDK for Java uses the ContainerCredentialsProvider to load these credentials. Instance profile credentials– used on EC2 instances, and delivered through the Amazon EC2 metadata service. The AWS SDK for Java uses the InstanceProfileCredentialsProvider to load these credentials. Note Instance profile credentials are used only if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is not set. See EC2ContainerCredentialsProviderWrapper for more information.

-randy

Much Appreciated, This gave me some insight, make some question raising to myself. We have AWS CLI installed on it. Since it is production I will do some non-business hours and get back to you. Will keep you posting.

Edited by: Pruthvi on Sep 12, 2019 7:45 AM

Hi Yes, it helped, I think the issue is with AWS CLI since according to profile EC2 is looking in AWS CLI I have tested different cases and set the version to an IAM role. Thank you very much for your help.

Add your answer

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions

Relevant questions

  • Lambda You do not have sufficient permission. Access denied. on root account.

  • Permission boundary on IAM role trust policy

  • 6000 SQS requests where I don't have any queues defined

  • We lost access to i-037efcb963119d88a and cant reboot it

  • is it possible that SQS Triggers to a Lambda Function Alias?

    Accepted Answer
  • How can I delete a "hidden" SQS

  • AWS Lambda: You do not have sufficient permission. Access denied

  • SQS Access Denied IAM - have full permission

  • Gave a user full access to SQS but it can still access absolutely no data

  • Access bucket s3 from a role on another account

What is the Sqsdefaultpolicy?

SQS queue policy is used to control user access to SQS queue. By default, only the account owner has access to queue, but the permissions can be changed to allow access by any user. If unrestricted access to a queue is allowed, anyone can manage the queue.

How do I delete AWS message in SQS?

Open the Amazon SQS console at https://console.aws.amazon.com/sqs/ ..
In the navigation pane, choose Queues..
On the Queues page, choose a queue..
Choose Send and receive messages. ... .
Choose Poll for messages. ... .
To delete messages, choose the messages that you want to delete and choose Delete..

How do I connect EC2 with SQS?

Step 1: Create an Amazon EC2 key pair. A key pair lets you connect to an Amazon EC2 instance. ... .
Step 2: Create AWS resources. ... .
Step 3: Confirm that your EC2 instance isn't publicly accessible. ... .
Step 4: Create an Amazon VPC endpoint for Amazon SQS. ... .
Step 5: Send a message to your Amazon SQS queue..

Can SQS be inside a VPC?

Amazon SQS now Supports Amazon VPC Endpoints using AWS PrivateLink. AWS customers can now access Amazon Simple Queue Service (Amazon SQS) from their Amazon Virtual Private Cloud (Amazon VPC) using VPC endpoints, without using public IPs, and without needing to traverse the public internet.