简体   繁体   中英

AWS EC2 IAM role for S3 access not working

I have an asp.net website running on an EC2 instance, this instance has an IAM role assigned to it with the AmazonS3FullAccess policy. This works fine for the website where I can upload, delete and get presigned URL's for images stored in my S3 bucket.

On the same EC2 instance I also have an asp.net API for a mobile application to access various data. When I try to get a presigned URL for an image stored in S3 using the API the following error is thrown.

Object reference not set to an instance of an object.

at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.FetchCredentials()
at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentials()
at Amazon.S3.AmazonS3Client.GetPreSignedURLInternal(GetPreSignedUrlRequest request, Boolean useSigV2Fallback)

The code for getting the presigned link is the same for the website and the API

Dim bucketRegion = RegionEndpoint.EUWest1
Dim s3Client As New AmazonS3Client(bucketRegion)
Dim request1 = New GetPreSignedUrlRequest
request1.BucketName = "mybucketname"
request1.Key = fileName
request1.Expires = DateTime.Now.AddMinutes(1080)
dim signedURL = s3Client.GetPreSignedURL(request1)

The error is thrown on the GetPreSignedURL line.

I can't figure out why the IAM role permissions work for the website but not the API hosted on the same server.

iam role does not have credentials locally and for creating the presigned url we need to have credentials.

aws iam get credentials asynchronously. So, we should call the presigned url function asynchronously if we are using iam role.

reference:

for .net : https://docs.aws.amazon.com/sdkfornet/v3/apidocs/index.html

for Nodejs: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getSignedUrl-property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM