I want to deploy a static site with CDK, I know that setting s3 bucket to public access is restricted since april 2023, So I decided to go with the OriginAccessIdentity route, but getting 403 when trying to access the domain name that is tied to the distribution and thisone to the s3 bucket.
this is my code so far:
const oai = new OriginAccessIdentity(this, siteDomain);
const siteBucket = new s3.Bucket(this, "SiteBucket", {
bucketName: siteDomain,
autoDeleteObjects: true,
publicReadAccess: false,
removalPolicy: RemovalPolicy.DESTROY, // not for production
websiteIndexDocument: "index.html",
websiteErrorDocument: "error.html",
});
new CfnOutput(this, "Bucket", { value: siteBucket.bucketName });
siteBucket.grantRead(oai);
const distribution = new Distribution(this, "Distribution", {
certificate: certificate,
defaultRootObject: "index.html",
domainNames: [siteDomain, domainName],
minimumProtocolVersion: SecurityPolicyProtocol.TLS_V1_2_2021,
errorResponses: [
{
httpStatus: 404,
responseHttpStatus: 404,
responsePagePath: "/error.html",
},
],
defaultBehavior: {
allowedMethods: AllowedMethods.ALLOW_ALL,
cachePolicy: CachePolicy.CACHING_DISABLED, // only for development
compress: true,
origin: new S3Origin(siteBucket, { originAccessIdentity: oai }),
originRequestPolicy: new OriginRequestPolicy(
this,
"OriginRequestPolicy",
{
headerBehavior: OriginRequestHeaderBehavior.all(),
queryStringBehavior: OriginRequestQueryStringBehavior.all(),
cookieBehavior: OriginRequestCookieBehavior.all(),
}
),
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
},
});
the error I get is:
Code: AccessDenied
Message: Access Denied
any advice will be appreciated.
2
Answers
The solution involves two main components:
In this code,
siteBucket.addToResourcePolicy(bucketPolicy);
adds the policy to the bucket, effectively applying the permissions defined in the policy.found the inspiration on this video https://www.youtube.com/watch?v=X9cdkqBgLbs
You can’t use OAI on a S3 bucket configured as a website endpoint.
You should configure the bucket as a custom origin and restrict access to served files with custom headers.