403 禁止在 AJAX 调用 restful 控制器内的非 restful 操作

403 Forbidden when doing AJAX call to non-restful action within restful controller

我有一个 Profile 模型,我正尝试通过 AJAX 更新它。

这是我的 routes.rb:

  resources :profiles do
    member do
      patch :speed_rating
      patch :dribbling_rating
      patch :passing_rating
      patch :tackling_rating
    end
  end

生成以下路由:

speed_rating_profile_path   PATCH   /profiles/:id/speed_rating(.:format)    
profiles#speed_rating

dribbling_rating_profile_path   PATCH   /profiles/:id/dribbling_rating(.:format)    
profiles#dribbling_rating

passing_rating_profile_path PATCH   /profiles/:id/passing_rating(.:format)  
profiles#passing_rating

tackling_rating_profile_path    PATCH   /profiles/:id/tackling_rating(.:format) 
profiles#tackling_rating

这是我的 ProfilesController:

class ProfilesController < ApplicationController
  before_action :set_profile, only: [:show, :edit, :update, :destroy, :invite_user, :speed_rating, :tackling_rating, :dribbling_rating, :passing_rating]
  authorize_resource except: [:dashboard]
  skip_authorization_check only: :dashboard

  def speed_rating
    binding.pry
  end

  def dribbling_rating
    binding.pry
  end

  def passing_rating
    binding.pry
  end

  def tackling_rating
    binding.pry
  end

  private
    def set_profile
      @profile = Profile.friendly.find(params[:id])
    end

    def profile_params
      params.require(:profile).permit(:id, :first_name, :last_name, :dob, :height, :weight, :bib_color, videos_attributes: [:id, :url, :video, :vimeo_url, :vimeo_embed_code, :official, :video_cache, :remove_video, :_destroy], transcripts_attributes: [:id, :url, :name, :transcript, :remove_transcript, :url_cache, :_destroy])
    end

在我的 profile.js 中,我正在这样做:

  var url = "/profiles/" + _profile_id + "/" + _rating_type + "_rating/?" + _rating_type + "=" + button.innerText

  $.ajax({
    type: "PATCH",
    url: url,
    success: function(result){
      console.log(_profile_id + "'s " + _rating_type + " was successfully updated.");
      console.log(result);
    },
    error: function(result){
      console.log(_profile_id + "'s " + _rating_type + " was successfully updated.");
      console.log(result);
    }
  })

这是我遇到的错误:

jquery.self-bd7ddd3….js?body=1:10255 PATCH http://localhost:3000/profiles/rebecca-nitzsche-st-george-s-college/dribbling_rating/?dribbling=6 403 (Forbidden)

编辑 1

我正在使用CanCanCan进行授权。

我尝试的一件事是将这些新操作添加到授权例外列表中,具体如下:

authorize_resource except: [:dashboard, :speed_rating, :dribbling_rating, :tackling_rating, :passing_rating]

到目前为止这似乎有效。但是,这会使我的应用不安全吗?

我如何让它在我正确授权的范围内工作,以确保没有用户在发现这些路由时可以滥用它们?

我假设这一行:

authorize_resource except: [:dashboard]

正在进行某种形式的身份验证或授权,这可能需要用户详细信息。在您的 AJAX 请求中,我看不到任何关于用户名或密码或会话 cookie 的规定。您需要确保发送带有 AJAX 请求的会话 cookie,以便成功授权请求。

您可以通过在对 $.ajax 的调用中包含一个 xhrFields 对象来做到这一点:

$.ajax({
    'type': 'PATCH',
    'url': 'whatever',
    'xhrFields': {
        'withCredentials': true
    }
    // whatever other AJAX options you need
});