0

Rails3.2アプリケーションでtoken_authが正常に機能するように考案しました。APIを構築しているだけで、デバイス認証メカニズムを別のトークンでオーバーライドする必要があります。なんで?1人のユーザーが多くの場所を持っているため、アカウント全体を危険にさらすことなく、このトークンを介して各場所への独立したアクセスを提供したいと考えています。

ロケーションが作成されると、ロケーションapi_tokenが自動的に作成されます。

新しいキーでアクセスしようとしているロケーションコントローラーで、これを試しました。

class Api::V1::LocationsController  < ApplicationController 

  before_filter :restrict_access, :only => :index


  def index
      @locations = Location.all
      @page_title = "Locations"
      @page_title_content = "A list of all your locations. Click to customise and view reports"

     respond_to do |format|
       format.json { render json: @locations }
       format.xml { render xml: @locations }
     end
   end


   private

   def restrict_access
     api_key = Location.find_by_api_token(params[:access_token])
     head :unauthorized unless api_key
    end

end

すべてが正常にルーティングされますが、ログインしておらず、URLにキーを渡さなくても、すべての場所を表示することが許可されています。

これを機能させる方法について何か提案はありますか?また、アクセスできる場所に表示される場所を制限するにはどうすればよいですか?通常、私はカンカンを使用しますが、これがどのように機能するかわかりません。

4

1 に答える 1

0

:token_authenticatabledevise では、 を使用してオーバーライドする必要がありますfind_for_token_authentication。これが私のアプリで機能するものです。

class User
  devise :token_authenticatable

  self.token_authentication_key = "access_token"

  def self.find_for_token_authentication conditions
    grant = AccessGrant.where(access_token: conditions[token_authentication_key]).
                         any_of({access_token_expires_at: nil}, {:access_token_expires_at.gt => Time.now}).
                         first

    if grant
      user = User.where(_id: grant.user_id).first
      user.current_grant = grant if user
      user
    end
  end
end

その後authenticate_user!、前のフィルターで標準を呼び出すだけです

class Api::BaseController < ApplicationController
  respond_to :json

  # don't protect from forgery here
  skip_before_filter :verify_authenticity_token
  before_filter :authenticate_user!
于 2012-06-19T10:35:59.617 に答える