Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CORS with Rails

Wu Qing
December 08, 2015

CORS with Rails

Presented at December 2015 meetup of Rorosyd - Ruby or Rails User Group Sydney
https://www.meetup.com/Ruby-On-Rails-Oceania-Sydney/events/225087753/

Wu Qing

December 08, 2015
Tweet

More Decks by Wu Qing

Other Decks in Programming

Transcript

  1. Why we need it API service on api.example.com Main site

    (front end) on www.example.com Make Ajax requests from the front end
  2. Same-origin policy "Cross-domain" Ajax requests are forbidden Prevent XSS and

    other security issues Ref: Same-origin policy on Wikipedia
  3. The brick walls are there for a reason. The brick

    walls are not there to keep us out. The brick walls are there to give us a chance to show how badly we want something. Because the brick walls are there to stop the people who don’t want it badly enough. They’re there to stop the other people. — Randy Pausch, The Last Lecture
  4. Cross-origin resource sharing 1. Browser send OPTIONS request with Origin

    header (http://www.example.com) 2. The server respond with Access-Control- Allow-Origin header 3. If match, continue with actual request; otherwise no request is made Ref: CORS on Wikipedia
  5. CORS with Rails Respond to the OPTIONS requests to every

    API endpoints Set appropriate headers (Origin, methods, headers) as needed
  6. Set the route namespace :api do resources :movies, :users #

    for the preflight request. Last route under /api match "*path" => "base#preflight_check", via: [:options] end
  7. Set headers for requests # Api::BaseController before_action :authenticate, :except =>

    [:preflight_check] after_action :cors_set_access_control_headers def preflight_check if request.method == 'OPTIONS' render :text => '', :content_type => 'text/plain' end end
  8. Set headers for requests def cors_set_access_control_headers headers['Access-Control-Allow-Origin'] = 'http://www.example.com' headers['Access-Control-Allow-Methods']

    = 'POST, PATCH, DELETE, OPTIONS' headers['Access-Control-Allow-Headers'] = 'X-MYCUSTOM-HEADER' headers['Access-Control-Max-Age'] = '10' # in seconds end
  9. Alternatives to CORS Same origin (not always feasible) JSONP (limited

    to GET; works on legacy browsers) Cross-document messaging