Skip to content

Instantly share code, notes, and snippets.

@AlexIoannides
Created August 23, 2016 21:40
Show Gist options
  • Save AlexIoannides/927dc77c8258ab436f602096c8491460 to your computer and use it in GitHub Desktop.
Save AlexIoannides/927dc77c8258ab436f602096c8491460 to your computer and use it in GitHub Desktop.
R function for generating URLs to S3 resources with query string request authentication.
#' Function for generating URLs to S3 resources with query string request authentication.
#'
#' @param path_to_file from the bucket and excluding leading '/'.
#' @param bucket the name of the S3 bucket containing the rescource.
#' @param region AWS region the bucket is located in.
#' @param aws_access_key_id access key ID for an IAM user with access to the S3 bucket.
#' @param aws_secret_access_key secret access key for an IAM user with access to the S3 bucket.
#' @param lifetime_minutes the duration in minutes after which the URL will expire.
#'
#' @return A URL to an S3 resource with query string request authentication.
#' @seealso \url{http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html#RESTAuthenticationQueryStringAuth} and,
#' \url{https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html}
#' @export
#'
#' @examples
#' path_to_file <- "index.html"
#' bucket <- "my.s3.bucket"
#' region <- "eu-west-1"
#' aws_access_key_id <- "DWAAAKIAJL4EWJCV3R36"
#' aws_secret_access_key <- "jH1pEfnVZJQtKj6OFDy+t253OZJWZLEo9gaEoFAY"
#' lifetime_minutes <- 1
#' aws_query_string_auth_url(path_to_file, bucket, region, aws_access_key_id, aws_secret_access_key, lifetime_minutes)
aws_query_string_auth_url <- function(path_to_file, bucket, region, aws_access_key_id,
aws_secret_access_key, lifetime_minutes) {
expiration_time <- as.integer(Sys.time() + lifetime_minutes * 60)
canonical_string <- paste0("GET", "\n\n\n", expiration_time, "\n/", bucket, "/", path_to_file)
signature <- digest::hmac(enc2utf8(aws_secret_access_key), enc2utf8(canonical_string), "sha1", raw = TRUE)
signature_url_encoded <- URLencode(base64enc::base64encode(signature), reserve = TRUE)
authenticated_url <- paste0("https://s3-", region, ".amazonaws.com/", bucket, "/", path_to_file,
"?AWSAccessKeyId=", enc2utf8(aws_access_key_id), "&Expires=", expiration_time,
"&Signature=", signature_url_encoded)
authenticated_url
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment