0

在我的Rails 4應用程序中,我創建了一個訪問控制器中的indexcreateshow,updatedestroy方法的API。過濾器使用前的軌跡

對於身份驗證,我使用HTTP基本身份憑證而不是用戶名和密碼(access_key = username,secret_key = passwordmaster_secret_key = password,以訪問某些方法)。

我想access_key/secret_key對只訪問createupdatedestroy方法和access_key/master_secret_key對,以允許訪問indexshow方法(以及其它的)。

身份驗證的作品,但我很難告訴Rails根據請求方法進行身份驗證的方式。

有什麼建議嗎?

下面是我到目前爲止的代碼:

class Api::V1::TestsController < ApplicationController 
    before_filter { :authenticate! || :authenticate_with_master! } 
    skip_before_filter :verify_authenticity_token 
    respond_to :json 

    def index 
    end 

    def create 
    end 

    def show 
    end 

    def update 
    end 

    def destroy 
    end 

    protected 

    def authenticate! 
    authenticate_or_request_with_http_basic do |access_key, secret_key| 
     @credential = Credentials.find_by_access_key(access_key) 
     (@credential.secret_key == secret_key) ? true : false 
    end 
    end 

    def authenticate_with_master! 
    authenticate_or_request_with_http_basic do |access_key, master_secret_key| 
     @credential = Credentials.find_by_access_key(access_key) 
     (@user.master_secret_key == master_secret_key) ? true : false 
    end 
    end 
end 

回答

2

嘗試用對的before_filter「只有」參數,並在軌道4,5

before_action :authenticate!, only: [:create, :update, :destroy] 

before_action :authenticate_with_master! , only: [:index, :show] 

希望這將有助於使用before_action。謝謝