使用API​​进行Rails令牌身份验证。令牌在哪里?

时间:2016-06-03 13:20:59

标签: ruby-on-rails authentication token api-design

首先,我对Rails相当新,这是我第一次尝试使用基于令牌的身份验证过程!

所以,在我的sessions_controller(客户端应用程序)中,我有这个片段从我的Rails API获取用户令牌:

#basic auth
uri_tk = URI.parse("http://localhost:3000/token")

http = Net::HTTP.new(uri_tk.host, uri_tk.port)
request = Net::HTTP::Get.new(uri_tk.request_uri)
request.basic_auth(params[:session][:email], params[:session][:password])
response = http.request(request)

在我的application_controller(api app)上,我有这个:

class ApplicationController < ActionController::API

 include ActionController::HttpAuthentication::Basic::ControllerMethods
 include ActionController::HttpAuthentication::Token::ControllerMethods

 before_filter :authenticate_user_from_token, except: [:token]

 include Authenticable

 respond_to :json

 def token
  authenticate_with_http_basic do |email, password|
    user = User.find_by(email: email)
    if user &&  user.match_password(password)
      render json: {token: user.auth_token}
    else
      render json: {error: 'Incorrect credentials' }, status: 401
    end
  end
 end

 private

  def authenticate_user_from_token
    unless authenticate_with_http_token { |token, options| User.find_by(auth_token: token)}
       render json: {erro: 'Bad Token'}, status: 401
    end
  end

end

所以,我的问题是:当我们到达所有后续请求需要通过“authenticate_user_from_token”的点时,没有令牌进行身份验证。我应该将令牌存储在客户端会话中吗?我是否必须在每个请求中指定令牌?

提前致谢!

0 个答案:

没有答案