vendredi 5 juin 2015

Upload file amazon s3 pre signed post

Im developing a web app from which Id like to upload files to Amazon S3, using a pre-signed post. Following the instructions on this link: http://ift.tt/1cXBgAh I have the following form.

<form action=<%= @aws_s3_url %> method="post" enctype="multipart/form-data">
      <input type="hidden" name="key" value= <%= @base_path + "${filename}" %> >
      <input type="hidden" name="AWSAccessKeyId" value= <%= @aws_access_key_id %> >
      <input type="hidden" name="acl" value="private">
      <input type="hidden" name="success_action_redirect" value=<%= "https://localhost:3000/projects/" + @project.id.to_s %> >
      <input type="hidden" name="policy" value= <%= @aws_policy %>>
      <input type="hidden" name="signature" value=<%= @aws_signature %>>
      <!-- Include any additional input fields here -->

      File to upload to S3:
      <input name="file" type="file">
      <br>
      <input type="submit" value="Upload File to S3">
    </form>

where @aws_s3_url = "http://ift.tt/1RPvfry"

The policy is generated with this method:

def generate_policy_pre_signed_post(key)
  policy = "{ \"expiration\": \"#{Time.now.tomorrow.utc.iso8601}\","
  policy +="\"conditions\": ["
  policy += "{\"acl\": \"private\" },"
  policy += "{\"success_action_redirect\": \"https://localhost:3000/projects/#{@project.id.to_s}\"},"
  policy += "{\"bucket\": \"my_bucket\" },"
  policy += "[\"starts-with\", \"$key\", \"#{key}\"],]}"

  policy
end

And then coded and signed like in the link above: policy = generate_policy_pre_signed_post("/users_data/" + user_creds.aws_identity_id + "/")

@aws_policy = Base64.encode64(policy).gsub("\n","")

@aws_signature = Base64.encode64(
  OpenSSL::HMAC.digest(
      OpenSSL::Digest::Digest.new('sha1'),
      server_credentials.secret_access_key, @aws_policy)
  ).gsub("\n","")

But when I try to upload a file to S3, it gives the following error: "The specified method is not allowed against this resource."

How can that be? In IAM my user has all the permissions to write to S3, and Ive also tried adding a bucket policy like this one:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "statement1",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::my_iam"
        },
        "Action": [
            "s3:PutObject"
        ],
        "Resource": [
            "arn:aws:s3:::my_bucket/*"
        ]
    }
]
}

Any ideas about what might be happening?




Aucun commentaire:

Enregistrer un commentaire