Spring Boot连接AWS S3失败:Access Key ID不存在(凭证确认正确)
Let's start with the most likely culprit here—it's a super common gotcha that trips up a lot of developers:
Issue 1: Unnecessary Quotes in Your Property Values
Looking at your application.properties, you've wrapped your access key and secret key in single quotes:
gkz.aws.access_key_id='AKIA5J4755OV2MAGNOUC' gkz.aws.secret_access_key='******'
Spring Boot reads these values including the quotes, so when your code passes 'AKIA5J4755OV2MAGNOUC' (with quotes) to AWS, it's not a valid access key ID—hence the InvalidAccessKeyId error.
Fix: Remove the Quotes
Update your properties to strip out those single quotes:
gkz.aws.access_key_id=AKIA5J4755OV2MAGNOUC gkz.aws.secret_access_key=****** gkz.s3.bucket=studileih2 gkz.s3.region=eu-central-1
Issue 2: Confusion Between IAM Roles and Long-Term Credentials
You mentioned creating an IAM role, but your current code uses long-term access keys/secret keys (which belong to an IAM user, not a role). If your app is running on AWS infrastructure (EC2, ECS, EKS, etc.), using an IAM role is far more secure and eliminates the need to hardcode credentials entirely.
How to Switch to IAM Roles:
- Attach the IAM Role to Your Resource: For example, if running on EC2, attach your IAM role (with
s3:PutObjectpermissions for thestudileih2bucket) to your EC2 instance. For ECS/EKS, assign the role to your task/pod. - Simplify Your S3 Config: Remove the hardcoded credential logic—AWS SDK will automatically fetch temporary credentials from the role:
@Configuration public class S3Config { @Value("${gkz.s3.region}") private String region; @Bean public AmazonS3 s3client() { return AmazonS3ClientBuilder.standard() .withRegion(Regions.fromName(region)) .withCredentials(DefaultAWSCredentialsProviderChain.getInstance()) .build(); } }
The DefaultAWSCredentialsProviderChain will automatically look for credentials in environment variables, instance metadata (for EC2), or other valid locations—no need to configure keys manually.
Additional Checks to Rule Out Other Issues
- Verify that your IAM user (if sticking with long-term credentials) has explicit permission to perform
s3:PutObjecton thestudileih2bucket. Double-check both your bucket policy and IAM user policies to ensure there's no denial in place. - Confirm your bucket is indeed in the
eu-central-1region (or that your SDK region matches the bucket's region—S3 buckets are region-specific, even though cross-region calls sometimes work with extra latency).
内容的提问来源于stack exchange,提问作者luda-chris

