0

I made an authentication api made with ruby on rails 5, and a react js frontend. It works by taking an email and password, and sending cookies back to the the browser. However when I try to make the request, the console shows the following error:

Access to XMLHttpRequest at 'http://localhost:3000/users/login' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

    #react component - signin.js

    axios(
        `http://localhost:3000/users/login`, {
        method: "post",
        withCredentials: true,        
        data: {email: this.state.email, password: this.state.password}
        })
    .then(response => {
        console.log(response)
    })
    .catch(error => console.log(error))

}

      #rails login function
           def login
          #fetch user
           user = User.find_by(email: params[:email].to_s.downcase)
            #authenticate method
              if user && user.authenticate(params[:password])
        #disallow unconfirmed emails
        if user.confirmed_at?
            auth_token = JsonWebToken.encode({user_id: user.id})
            ##
            cookies.signed[:jwt] = {value:  auth_token, httponly: true}

            render json: {auth_token: auth_token, email:user.email}, 
              status: :ok


          else
            render json: {error: 'Email not verified' }, status: 
             :unauthorized
        end
    else
      render json: {error: 'Invalid username / password'}, status: 
            :unauthorized
    end
  end
Chiro Ogbo
  • 11
  • 4

1 Answers1

0

I think You should use rack cors.

  1. Add gem 'rack-cors' in your rails app Gemfile

    gem 'rack-cors'

  2. Add below code to config/application.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins 'example.com' resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head] end end

Instead of 'example.com' in origins, you can provide your origin endpoint or use '*' to allow all.

Shan
  • 613
  • 9
  • 21