2014-02-15 3 views
0

HTTP 헤더에 포함 된 인증 토큰이 사용자 테이블에 저장된 토큰과 일치하는 경우에만 리소스에 대한 액세스를 허용하려고합니다. 리소스에 액세스하기 위해 다음과 같이 나는 컬 사용하고 있습니다 :인증 HTTP 헤더에서 인증 토큰 값 가져 오기

$ curl http://localhost:3000/api/v1/tasks.json -H 'Authorization: Token token="S8S4MPqFNdDz3G1jLsC9"'

tasks#index 방법에 내가 토큰은 위의 데이터베이스에 저장된 현재 사용자의 인증 토큰을 일치하는지 여부를 확인하고 싶습니다. 아래 그림과 같이 내가 사용할 수 있도록 인스턴스 변수로 토큰 값을 얻을 수있는 방법 이 railscast,에서

def index 
    @token = ??? 
    if User.exists?(:authentication_token => @token) 
    ### code to access the resource 
    else 
    authenticate_user! 
    end 
end 

답변

1

내가 최고의 솔루션을 발견은 authenticate_or_request_with_http_token 방법과 같이 레일을 사용하는 것입니다

class Api::V1::TasksController < ApplicationController 
    before_filter :restrict_access 
    respond_to :json 

    def index 
    @user = User.where("users.authentication_token IS NOT NULL").first 
    @tasks = @user.tasks 
    end 

private 

    def restrict_access 
    authenticate_or_request_with_http_token do |token, options| 
    User.exists?(authentication_token: token) 
    end 
end