1

I am struggling to get gem "rack-cors" to work locally. I have bare rails setup with gem 'devise_token_auth' and angular 7 client with 'angular-token' for auth. But every request from angular is throwing cors error. I have configured rails and "rack-cors" as per documentation but its not working. Here's my configuration in application.rb

config.middleware.insert_before 0, 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

If I list Middlewares using rails middleware, Rack::Cors is listed second after use Webpacker::DevServerProxy but every request throws following error.

Processing by DeviseTokenAuth::SessionsController#create as HTML
  Parameters: {"session"=>{}}
HTTP Origin header (http://localhost:4200) didn't match request.base_url (http://localhost:3000)
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)



ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
quazar
  • 570
  • 4
  • 14

1 Answers1

0

It turns out I need to change how protect_from_forgery was handled as mentioned in docs

protect_from_forgery with: :null_session

PS: To the person who deleted his answer, please don't do that, knowing what not to do is also part of leaning.

quazar
  • 570
  • 4
  • 14
  • **Be warned:** this is a terrible idea (in OP's case - note they are using HTML). By doing this you are turning off a key security feature in Rails, which exposes you to CSRF. – jakenberg Sep 10 '19 at 00:29
  • @jakenberg I am using JSON API so its not an issue. – quazar Sep 11 '19 at 15:00
  • JSON APIs can still be vulnerable to CSRF via XSS: https://security.stackexchange.com/a/150877/40855. Update your question so that it doesn't show you rendering as HTML if this is a JSON API question. – jakenberg Sep 13 '19 at 02:36