且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails,设计身份验证,CSRF 问题

更新时间:2023-12-06 09:01:22

Jimbo 出色地解释了您遇到的问题背后的原因".您可以采用两种方法来解决此问题:

Jimbo did an awesome job explaining the "why" behind the issue you're running into. There are two approaches you can take to resolve the issue:

  1. (由 Jimbo 推荐)覆盖 Devise::SessionsController 以返回新的 csrf-token:

  1. (As recommended by Jimbo) Override Devise::SessionsController to return the new csrf-token:

class SessionsController < Devise::SessionsController
  def destroy # Assumes only JSON requests
    signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
    render :json => {
        'csrfParam' => request_forgery_protection_token,
        'csrfToken' => form_authenticity_token
    }
  end
end

并在客户端为您的 sign_out 请求创建一个成功处理程序(可能需要根据您的设置进行一些调整,例如 GET 与 DELETE):

And create a success handler for your sign_out request on the client side (likely needs some tweaks based on your setup, e.g. GET vs DELETE):

signOut: function() {
  var params = {
    dataType: "json",
    type: "GET",
    url: this.urlRoot + "/sign_out.json"
  };
  var self = this;
  return $.ajax(params).done(function(data) {
    self.set("csrf-token", data.csrfToken);
    self.unset("user");
  });
}

这还假设您在所有 AJAX 请求中自动包含 CSRF 令牌,如下所示:

This also assumes you're including the CSRF token automatically with all AJAX requests with something like this:

$(document).ajaxSend(function (e, xhr, options) {
  xhr.setRequestHeader("X-CSRF-Token", MyApp.session.get("csrf-token"));
});

  • 更简单,如果它适合您的应用程序,您可以简单地覆盖 Devise::SessionsController 并使用 skip_before_filter :verify_authenticity_token 覆盖令牌检查.

  • Much more simply, if it is appropriate for your application, you can simply override the Devise::SessionsController and override the token check with skip_before_filter :verify_authenticity_token.