Search code examples
ruby-on-railsamazon-web-servicesamazon-s3carrierwaveamazon-cloudfront

Rails S3 - CloudFront 401 error triggers Basic Auth popup


I have a Rails app with carrierwave uploaders configured to use carrierwave-aws on an S3 bucket.

The permissions for that bucket WERE bad, but hopefully I fixed them and now uploads seem to work fine (and I checked the permissions of a single file, public read is checked)

The Rails app is using cloudfront, which has been configured to handle "normal" assets (css, js, etc.) and with carrierwave-aws.

However I am still getting 401 errors, and worse, when this happens a HTTP Basic auth popu appears on screen, asking for a password for my distribution

"NetworkError: 401 Unauthorized - https://xxxxxxx.cloudfront.net/uploads/user/avatar/xxxxxx/thumb_avatar.jpg"

The above error triggers an HTTP Basic auth windows asking for the user/pw for xxx.cloudfront.net

If this is linked, it turns out I indeed do have this kind of auth on my Rails website itself (before we move on to production).

On CloudFront, I have configured two origins : my Rails server (and css/js are ok so I guess this ons is fine) and The S3 Bucket (don't know how I can really test this one though)

So

  • How can I check My Rails -> Carrierwave-aws -> CloudFront pipeline is working fine ? (Uploads are fine, I just can't read from the browser after an upload)
  • How can I disable HTTP Basic Auth from the website in case a 401 error appears ?

EDIT : I setup Basic Auth in Rails ApplicationController

def authenticate
    if ENV["HTTP_BASIC_AUTH"] == "true"
      authenticate_or_request_with_http_basic do |username, password|
        username == "wxx" && password == "xxx!" or
      end
    end
  end

Solution

  • A 401 HTTP response is, of course, supposed to trigger a browser pop-up prompt. If you don't want that, your solution is not to require auth in your application.

    But, it seems like the solution that would be most helpful to you at this point would be to go ahead and enable pass-through of the browser's attempt to send credentials back to the origin server. To do this, CloudFront needs to forward the Authorization: header to your origin. By default, this request header (like most request headers) us discarded by CloudFront and not sent to the origin.

    Whitelist this header in the appropriate cache behavior so that CloudFront will forward it and your access control mechanism should work as expected.

    Remember that changes to CloudFront distributions take a few minutes. Wait for the distribution to return to the deployed status before testing.