Devise AJAX - POST request: current_user is null

I am trying to develop a one-page authentication application. I am using Devise (Rails) and AngularJS. For some other reason, my rails application and my angularjs application are not on the same server. So, I have to handle cross domain issues ... And I can't send the X-CSRF token to my header. I can correctly log in and out and send a GET request without any problems. In my rails controllers, I can use current_user, it is set correctly. However, when I submit a POST request, current_user is NULL. It seems my session_id is not sent. The problem is with the cross-domain, because if I send my ajax request from the same server, this is normal.

I think I have 2 solutions: - Do not use cookie-based authentication, but use a token - Put the interface and end on the same server.

Other ideas? Why is current_user null when I submit a POST request from a cross domain?

+4
source share
1 answer

You can send the CSRF token to the headers, ANYTHING is a bad practice that reveals some security holes ( issue a stream on github, explaining why )

The safest way to do this is to disable CSRF together:

class ApplicationController < ActionController::Base # or use Api::BaseController < ApplicationController if you are namespacing # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :null_session end 

And use token based authentication, which you can implement yourself or use devess: token_authenticatable. You will need to configure AngularJS to send the token in either the parameters or the headers. Here is a snippet that I use to define rails if the token is in the headers or parameters.

 class Api::BaseController < ApplicationController prepend_before_filter :get_auth_token private def get_auth_token if auth_token = params[:auth_token].blank? && request.headers["X-AUTH-TOKEN"] params[:auth_token] = auth_token end end end 

So in the end how it works:

  • The client uses the login method that you defined for authentication
  • Gets the authentication token from the server
  • Uses a token in each subsequent request for authorization
+4
source

Source: https://habr.com/ru/post/1481529/


All Articles