0

I'm developing a Ionic(Cordova) app with a Ruby on Rails API. I want to use response headers to return a token after login. I'm using rack-cors gem to make Cross Origin Request work:

application.rb

config.middleware.insert_after Rails::Rack::Logger, Rack::Cors, :logger => Rails.logger do
      allow do
        origins '*'
        resource '/api/*', :headers => :any, :methods => [:get, :post, :options, :put]
      end
    end

and grape gem to manage my API routes. But i can't find a way to add a header to my response since i added rack-cors.

I tried this:

header('Access-Token', user.token.key)

But it doesn't work. Whatever i do i end up with those headers:

{cache-control: "max-age=0, private, must-revalidate", content-type: "application/json"}

Can anyone help me with this issue ?

Community
  • 1
  • 1
Shrolox
  • 663
  • 6
  • 22
  • can u add these to application_controller.rb and remove your current protect_from_forgery. add `protect_from_forgery with: :exception, if: Proc.new { |c| c.request.format != 'application/json' } protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }` – 7urkm3n Apr 04 '16 at 15:37
  • if yr working locally and calling rails api, it should not give you rack-cord as i know. Im just not experienced with cordova. – 7urkm3n Apr 04 '16 at 15:40
  • Indeed i'm working locally. i tried to change my protect_from_forgery as you suggested, but it gives me the well known 'Access-Control-Allow-Origin' error – Shrolox Apr 04 '16 at 15:42
  • And ionic can be emulated in my browser, just so you know, so it's pretty much an Ajax request that i'm doing – Shrolox Apr 04 '16 at 15:43
  • http://localhost:3007/api/login – Shrolox Apr 04 '16 at 15:44
  • what r u using for login devise ? – 7urkm3n Apr 04 '16 at 15:45
  • yes i'm using devise – Shrolox Apr 04 '16 at 15:46
  • if devise, use this one `https://github.com/lynndylanhurley/devise_token_auth` it will be totally fine as i know. – 7urkm3n Apr 04 '16 at 15:46
  • Thanks i'll try that – Shrolox Apr 04 '16 at 15:47

1 Answers1

3

I used gem 'devise_token_auth'

Also, i had this configuration in application.rb.

  class Application < Rails::Application
    # Do not swallow errors in after_commit/after_rollback callbacks.
    config.active_record.raise_in_transactional_callbacks = true

    config.middleware.use Rack::Cors do
      allow do
        origins '*'
        resource '*',
          :headers => :any,
          :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
          :methods => [:get, :post, :options, :delete, :put]
      end
    end

  end
7urkm3n
  • 6,054
  • 4
  • 29
  • 46
  • Just pointing that the custom header needs to be lower-cased when declared in the `expose` key. – lgx Nov 15 '18 at 09:07