IAM Policy for S3 Access Restricted to a Prefix
Create an IAM policy limiting S3 access to objects under a specific prefix (folder path). Useful for multi-tenant applications and per-user storage.
Storage
Detailed Explanation
Prefix-Based S3 Access Control
In multi-tenant applications or shared buckets, you often need to restrict each user or service to their own "folder" (prefix). IAM policies can enforce this by scoping the Resource to a specific prefix pattern.
Policy JSON
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowListBucketWithPrefix",
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::shared-bucket",
"Condition": {
"StringLike": {
"s3:prefix": ["uploads/user-123/*"]
}
}
},
{
"Sid": "AllowObjectAccessUnderPrefix",
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject"
],
"Resource": "arn:aws:s3:::shared-bucket/uploads/user-123/*"
}
]
}
Two-Statement Design
- Statement 1 allows
ListBucketon the bucket but uses a Condition to restrict listing to objects under theuploads/user-123/prefix only. Without the condition, the user could list all objects in the bucket. - Statement 2 grants object-level operations (Get, Put, Delete) but only for resources matching the specific prefix ARN pattern.
Dynamic Prefix Policies
In practice, you often use IAM policy variables like ${aws:username} or ${aws:PrincipalTag/tenant-id} to make the prefix dynamic:
"Resource": "arn:aws:s3:::shared-bucket/uploads/${aws:PrincipalTag/tenant-id}/*"
This eliminates the need to create a separate policy per user or tenant.
Use Case
Multi-tenant SaaS applications where each tenant's data is stored under a unique S3 prefix, ensuring data isolation at the IAM level without separate buckets.