ruby-on-rails - 设计 AJAX - POST 请求 : current_user is null

标签 ruby-on-rails angularjs devise cross-domain

我尝试开发带有身份验证的单页应用程序。我使用设计(Rails)和 AngularJS。
由于某些不同的原因,我的 rails 应用程序和我的 angularjs 应用程序不在同一台服务器上。所以,我必须处理跨域问题......而且我无法在我的 header 中发送 X-CSRF-Token。
我可以正确登录和注销并毫无问题地发送 GET 请求。在我的 rails Controller 中,我可以使用 current_user,它已正确设置。
但是,当我发送 POST 请求时,current_user 为空。看来我的 session_id 没有发送。问题是由于跨域,因为如果我从同一台服务器发送我的ajax请求,就可以了。

我想,我有两个解决方案:
- 不要使用基于 cookie 的身份验证,而是使用 token
- 将前端和后端放在同一台服务器上。

其他想法?当我从跨域发送 POST 请求时,为什么 current_user 为空?

最佳答案

您可以在 header 中发送 CSRF token ,但是这是一种暴露一些安全漏洞的不好做法( issue thread on github explaining why )

最安全的方法是禁用 CSRF全部一起:

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

使用基于 token 的身份验证,您可以 implement yourself或使用设计的 :token_authenticable。您必须配置 AngularJS 以在 params 或 headers 中发送 token 。这是我用来让 rails 确定 token 是否在标题或参数中的片段。
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

所以最终它是如何工作的:
  • 客户端使用您定义的登录方法进行身份验证
  • 从服务器获取身份验证 token
  • 在每个后续请求中使用 token 进行授权
  • 关于ruby-on-rails - 设计 AJAX - POST 请求 : current_user is null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16626091/

    相关文章:

    ruby-on-rails - 从 jail 长或设计中获取 session ID

    ruby-on-rails - 帮助使用带有内置 Omniauth 支持的设计

    ruby-on-rails - 使用 RSpec 测试使用 CanCan 和 Devise 的 View

    MySQL正则表达式: How to match digits in the string with\d?

    ruby-on-rails - 在 Rails 中使用 Postgres UUID 时破坏了加入记录的创建、保存、更新和销毁

    javascript - 在 ng-bind-html 的结果之间添加空格

    javascript - 从 Controller 切换类并以 Angular 更新 View

    ruby-on-rails - ActiveRecord 加入 ID 数组

    javascript - 通过 AJAX 提交表单而不重新加载页面

    javascript - 如何使元素的高度等于 Ionic 中的宽度?