Back End/AWS
[AWS] Setting up Cloudfront signed cookies for multiple paths in Java, Kotlin
DevPing9_
2023. 5. 1. 18:29
What we need to do
1. Find AWS SDK Library
2. Assgin openssl rsa public key to Cloudfront
3. Set SignedCookie to Response in Application Code
Example Kotlin Code
fun getBookContentResponse(
req: HttpServletRequest,
res: HttpServletResponse,
bookContentId: String
): BookContentResponse {
val expireCalendar = Calendar.getInstance()
expireCalendar.add(Calendar.MINUTE, 60)
val resourcePath = "$bookContentId/*"
val privateKeyFile = File(privateKeyLocation)
val cookies = CloudFrontCookieSigner
.getCookiesForCustomPolicy(
SignerUtils.Protocol.https, // e.g. "https" (not `https://`)
contentCloudFrontFQDN, // e.g. "www.abc.com" (FQDN needed, not Root Domain)
privateKeyFile, // private key for Cloudfront public key
resourcePath, // e.g. "image/*" (not `/image/*`)
cfPubKey, // CloudFront public key id (you can find it in AWS Console)
expireCalendar.time, // Signed Cookie expiredAt
null, // Signed Cookie activeFrom (if null, it starts as soon as it is issued)
null // Signed Cookie Allowed IP (if null, there's no retriction for client IP)
)
val url = SignerUtils.generateResourcePath(SignerUtils.Protocol.https, contentCloudFrontFQDN, resourcePath)
res.addCookie(makeSignedCookie(cookies.getPolicy().key, cookies.getPolicy().value))
res.addCookie(makeSignedCookie(cookies.signature.key, cookies.signature.value))
res.addCookie(makeSignedCookie(cookies.keyPairId.key, cookies.keyPairId.value))
return BookContentResponse(baseUrl = url.substring(0, url.length - 2))
}
fun makeSignedCookie(key: String, value: String): Cookie {
val cookie = Cookie(key, value)
cookie.domain = getRootDomain(contentCloudFrontFQDN) // you can customize
cookie.path = "/"
cookie.isHttpOnly = true
cookie.secure = true
return cookie
}
728x90