Heroku and Amazon CloudFront Cross-Origin Resources Sharing and Image URL - ruby-on-rails

I have 1 question and 1 issue:
Question: If using CloudFront, is the image URL supposed to have s3.amazonaws.com or randomblah.cloudfront.net?
http://s3.amazonaws.com/bucketname/project_images/photos/000/000/006/medium/IMG_3867.JPG?1438009375
or with the actual cloudfront.net url...
http://fdawfwe8200.cloudfront.net/bucketname/project_images/photos/000/000/006/medium/IMG_3867.JPG?1438009375
Right now, I have this in my production.rb
config.action_controller.asset_host = 'fdawfwe8200.cloudfront.net'
Issue: I'm getting Redirect at origin 'http://fdawfwe8200.cloudfront.net' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header.... error
How do I fix this?
The only thing I see breaking on my site is, bootstrap icons are boxes.

you can find documentation to help CloudFront with your Cors configuration like here:
http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#request-custom-cors
So just let your content server specifiy the 'Access-Control-Allow-Origin' header to what you want and configure your CDN to keep those headers.

Related

(Some) webfonts not loading through Cloudfront using Heroku

I'm hosting a website on Heroku using Ruby on Rails. It uses a Cloudfront distribution to serve assets, and S3 to store images.
When going to http://example.com, everything works fine except for 2 webfonts. All the other fonts load fine.
When going to http://www.example.com, none of the webfonts load.
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.example.com' is therefore not allowed access.
I was using the normal Cloudfront asset host d12345.cloudfront.net, but I figured if I switched to assets.example.com, I'd outsmart the CORS issues. But I'm still getting:
Access to Font at 'http://assets.example.com/assets/myfont-Bold-735639b52225ec60e258c2b8b193dfb479f6158c3738a595db04f3a9684a4ad8.woff' from origin 'http://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.example.com' is therefore not allowed access.
```
I have read countless threads, blogposts, SO answers about this issue but I can't seem to figure it out.
I have set up Rack::Cors in my rails application as follows:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '/assets/*', headers: :any, methods: [:get]
end
end
My asset_host is set up correctly:
CLOUDFRONT_HOST = "http://assets.example.com"
config.action_controller.asset_host = CLOUDFRONT_HOST
All other assets work perfectly fine. Images, JavaScript, CSS all come from CloudFront without any hiccups. It's just the 2 webfonts when going to the www.example.com subdomain and all webfonts when going to the root level site example.com.
I have tried a number of options in the Cloudfront and S3 admin panels:
added cors config to my bucket
whitelisted headers in my cloudfront distribution
But nothing seems to work. I'm lost as to why those 2 fonts won't load properly while everything else works fine.
Fonts are usually checked by your browser preflight, with an OPTIONS request. In your CORS setup, try also allowing OPTIONS in addition to GET. You might also have to allow OPTIONS on your CloudFront distribution.
Note that if these fonts have a query parameter in the request url, like assets.example.com/font.woff?v=123, the CloudFront distribution should also forward query parameters.

making a request to an insecure endpoint(http)

I have been having an issue with my rails app not generating https assets. I have set config.action_controller.asset_host equal to https:// version of my cloudfront assets but I still seem to get:
Mixed Content: The page at URL was loaded over HTTPS, but requested an insecure font 'http://cloudfront.net/assets/fontawesome-webfont'. This request has been blocked; the content must be served over HTTPS.
I have set cloudfront to https only but it still seems to be generating the http version. I can see where it sets the fontAwesomePath but I can't seem to find where it is being included.
I am uncertain as to why it is still being delivered as an http resource and would appreciate any advice
Much Appreciated
chaddpaul

No 'Access-Control-Allow-Origin' header is present on the requested resource

I am using omniauth-facebook with AngularJS and CORS is not working correctly .
My omniauth.rb is
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook,"xxxxx", "xxxxx",
:scope => 'email,user_birthday,read_stream', :display => 'popup'
end
Everything works if i use it as rails app and request. But when i try to call 'http:\localhost:3000\users\auth\facebook" via Angular JS
$http.get('/users/auth/facebook').success(function(data, status, headers, config) {
console.log("back in success");
}).
error(function(data, status, headers, config) {
});
}
i see following error in JS console
XMLHttpRequest cannot load
https://www.facebook.com/dialog/oauth?client_id=xxxx&display=popup…thday%2Cread_stream&state=3352c1924bdbc9277f7b1070c38d67acf79b529f198323cb.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
(The url is not displayed completely in console)
I added following line
config.middleware.insert_before Warden::Manager, Rack::Cors
but also this didn't work .
What is the best way or how can i override headers for OmniAuth ?
I am using Angularjs and gem devise ,omniauth-facebook
Since you are on your development environment you may want to try a workaround, by allowing you browser to run in a non-secure mode.
For Chrome on Windows, from CMD try:
> cd C:\Program Files (x86)\Google\Chrome\Application
> chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
The --disable-web-security flag will allow you to make cross domain requests. The --user-data-dir flag will allow you to open a new session only for development.
This is just a workaround for you development work! Don't use this in production or navigate to other sites in this session!
The issue is Javascript cannot make cross-domain requests. This is done for security reasons so that a script cannot call a remote server and expose sensitive data.
Below is a link to a very good and simple explanation with a few options on how to get around it:
http://developer.yahoo.com/javascript/howto-proxy.html
And here is a previous answer which has some good information as well:
Why am I seeing an "origin is not allowed by Access-Control-Allow-Origin" error here?
If they don't have the header set then you can't force them to have the headers. Perhaps you should look at using JSONP. However, mirroring through the server wouldn't be all that bad since you'll only have to deal with it at most once per visit, and more than likely once per user since so few people ever delete cookies.
Set 'Access-Control-Allow-Origin' in server will make the track.
Like:
ruby
headers['Access-Control-Allow-Origin'] = '*'
In rails.
The problem is you are getting the data from the https secure site that is facebook to your site which is http so the latest browsers are not supporting cross allow origin.
The only solution is make your site support https.
In your ApplicationController.rb add
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = 'http://localhost:3000'
end
For CORS you have to whitelist the domain you want to access from cross origin request on the server side
headers['Access-Control-Allow-Origin'] = '*'
//star will allow all the domain you can specify also which url u want to access
on the client side,you have to set the header in config() as
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
some times that problem occurs because of browser.IE by default allow cross origin request. In chrome you will required to add one plugin that is "Allow-Control-Allow-Origin: *"and enabled it.

Firefox does not render fonts from CloudFront

I have a Rails app, hosted on Heroku. During deployment assets are synced with an Amazon S3 bucket via the asset_sync gem and views call those assets through CloudFront. However, fonts are not rendered when viewing the website with Firefox (files are loaded in the Net tab of Firebug, but simply not used). Safari works great.
I have the following CORS config on S3:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Content-*</AllowedHeader>
<AllowedHeader>Host</AllowedHeader>
</CORSRule>
</CORSConfiguration>
My app also sets the following headers:
Access-Control-Allow-Origin: *
Access-Control-Request-Method: *
But CloudFront returns fonts without them... Why aren`t fonts loaded?
Thanks in advance.
Some versions of Internet Explorer and Firefox consider fonts an attack vector and will refuse loading them if they are being provided by another domain (cross domain policy).
On standard HTTP servers all you need to do is add the Access-Control-Allow-Origin: * header to bypass the CORS policy. The problem is S3 doesn’t support sending it. (Though according to the specification it should support CORS, the header is not sent).
There is a workaround. CloudFront can be pointed at another server that can send the Access-Control-Allow-Origin header (You can do that with the server that serves your app ;) ).
This can be done by adding a Custom Origin to your CloudFront distribution from the AWS Console. Next you will have to add Behaviours with your font types and the newly added Origin. You can use wildcards for the filename. (You’ll need to do this once for each font type that you have).
Example:
Path Pattern: /assets/*.woff
When ready you can validate the header existence with:
curl -I http://cloudfrontid.cloudfront.new/assets/font.woff
Hopefully you will see the Access-Control-Allow-Origin header, provided by your server along with the file itself, cached by CloudFront with the header included.
Hope it helps!
Try invalidating your (cached) font files in Cloudfront: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#invalidating-objects-console
I had a similar issue today. I read an article that suggested CORS configurations are cached in CloudFront. I resolved my issue by invalidating my font files.
On June 26, 2014 AWS added support for CORS in CloudFront, so now you can make this work with just CloudFront and S3.
This SO answer provides info about enabling CORS support for a particular CloudFront distribution:
https://stackoverflow.com/a/24459590/3195497
In addition you will need to enable CORS on your S3 bucket. One of the answers here says in regard to S3:
Though according to the specification it should support CORS, the
header is not sent
From my testing this is only partially true. If the Origin header is sent in the request then S3 will correctly send the Access-Control-Allow-Origin header. If the Origin header is not sent then S3 will not send the Access-Control-Allow-Origin header.
In the past this has caused problems with CloudFront. If you made any requests to CloudFront without an Origin request header then CloudFront will cache a response without the Access-Control-Allow-Origin response header. This might happen because you are testing the asset with a curl command and you don't include the Origin request header. Now when you make a request to CloudFront with the Origin header, CloudFront would ignore the Origin header and serve the cached response without the Access-Control-Allow-Origin header.
With the changes recently released to CloudFront, you can configure your distribution to take the Origin request header into account. In this case CloudFront will cache different responses, one response for each value of the Origin header.
This is what my CORS config looks like. I have a different AllowedHeader than you. I don't use asset_sync.
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Rails: activating SSL support gets Chrome confused

There is a nice option to config for the Rails app:
config.force_ssl = true
However it seems that just putting that to true doesn't get the HTTPS connections working. Even more - after trying (and failing) to connect to https://localhost:3000 with Chrome, I've set this option to false, and Chrome still tries to open https, even if I write http.
So, couple of questions:
--How to force Chrome not to try https anymore?
--What is the proper way of enabling SSL on my Rails app?
Update: The app is run on Heroku, and it seems that https is supported there automagically. Can I test SSL also locally? Like when running rails server?
First, I should say that I haven't tried this, but there are mainly two possibly reasons for Chrome still using HTTPS:
Using HTTP Strict Transport Security headers: if the server sets them, the client (supporting HSTS, like Chrome) is meant to stick to HTTPS for all subsequent requests to that host.
Permanent redirects. If the initial redirect you got was using "301 Moved Permanently" (and not 302 for example) to make the redirection,(*) the browser is meant to remember it ("The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs").
A likely solution to this would be to clear the cache in your browser.
(*) This question seems to indicate this is the case for Ruby on Rails with this config).
I had the same issue. What I did is using an ssl enforcer gem which adds a middleware that handles ssl and redirects. It has a strict option which enforces the configured protocols.
in your Gemfile add:
gem 'rack-ssl-enforcer'
in production.rb add:
config.middleware.use Rack::SslEnforcer, only: %r{your_regex_condition}, strict: true
This will force the requested pages to be secured and the rest to be non secured. It disables the HSTS header which is problematic in chrome (redirect caching issue).
You can also expire the cache for all cleints (if it already exist) to make sure you'll not get infinite redirect:
config.middleware.use Rack::SslEnforcer, only: %r{your_regex_condition}, :hsts => { :expires => 1, :subdomains => false }
also remove the ssl enforcement in production.rb (otherwise it might conflict with this middleware):
config.force_ssl = false
Let's see what happened once you updated your config file with:
config.force_ssl = true
This has caused Rack SSL Middleware to be loaded as the first middleware. As you can see in the code, Rack SSL sets an HSTS header by adding this line to the headers :
Strict-Transport-Security
It tells supported browsers such as Chrome to use HTTPS only to access your website.
So once you set back :
config.force_ssl = false
Chrome will still uses HTTPS to access your website and causes an error.
To solve this problem, you need to empty the HSTS cache. You can to that by going to the following url in your chrome browser :
chrome://net-internals/#hsts
Open your Chrome Developer Tools when you're at localhost: Then you can right click the refresh button ↻ and select "Empty cache and hard reload".
This error might also happens to you, if you start your server in the production environment, where HSTS is enabled.
Chrome redirects you to https://localhost:3000/ and says "SSL connection error".

Resources