Skip to content

Instantly share code, notes, and snippets.

@sscotth
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sscotth/6923c01a4b8d6b0b1fde to your computer and use it in GitHub Desktop.
Save sscotth/6923c01a4b8d6b0b1fde to your computer and use it in GitHub Desktop.
S3 File upload

Generate encoded policy and form signature

Run irb and execute the following commands with your bucket name and AWS secret key. You will need to save the encoded_policy string and the signature.

require 'base64'
require 'openssl'
require 'digest/sha1'

aws_secret_key = 'SKYBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXJoYL'
policy_json = '{"expiration":"2020-01-01T00:00:00Z","conditions":[{"bucket":"omgttt-sscotth-io-images"},{"acl": "public-read"},["starts-with","$Content-Type",""],["starts-with","$key",""]]}'

encoded_policy = Base64.strict_encode64(policy_json).gsub('\n','')
signature = Base64.strict_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'),aws_secret_key,encoded_policy)).gsub('\n','')

Results in:

encoded_policy = eyJWZXJXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXdfV19
signature = alvIBnXXXXXXXXXXXXXXXXXXcsA=

Add CORS configuration to bucket permissions:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1418963950000",
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:PutObjectAcl"
      ],
      "Resource": [
        "arn:aws:s3:::omgttt-sscotth-io-images/*"
      ]
    }
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment