Devise令牌认证的API路由

时间:2014-01-15 16:04:43

标签: ruby-on-rails ruby ruby-on-rails-3 authentication devise

我在Rails 3应用程序中使用Devise进行用户身份验证。此应用程序还提供对移动应用程序的API响应。我读到Devise因各种原因删除了令牌身份验证功能,并且我已根据这个要点在我的应用程序中实现了它:https://gist.github.com/josevalim/fb706b1e933ef01e4fb6

class ApplicationController < ActionController::Base
  protect_from_forgery

  # before_filter :authenticate_user_from_token!
  before_filter :authenticate_user! # Devise's default auth

  private

  def authenticate_user_from_token!
    user_email = params[:user_email].presence
    user       = user_email && User.find_by_email(user_email)

    if user && Devise.secure_compare(user.authentication_token, params[:user_token])
      sign_in user, store: false
    end
  end

end

以下是负责API响应的控制器的第一部分:

class ApiController < ApplicationController

  before_filter :cors_preflight_check
  after_filter :cors_set_access_control_headers

  before_filter :authenticate_user_from_token!

  # For all responses in this controller, return the CORS access control headers.

  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, OPTIONS'
    headers['Access-Control-Max-Age'] = "1728000"
  end

  # If this is a preflight OPTIONS request, then short-circuit the
  # request, return only the necessary headers and return an empty
  # text/plain.

  def cors_preflight_check
    if request.method == :options
      headers['Access-Control-Allow-Origin'] = '*'
      headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, OPTIONS'
      headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version'
      headers['Access-Control-Max-Age'] = '1728000'
      render :text => '', :content_type => 'text/plain'
    end
  end

  ... (response methods)

我的HTTP请求路由:

scope(:path => '/api/v1.0/') do
  match '/candidates' => "api#candidates"
  match '/districts' => "api#districts"
  match '/articles' => "api#articles"

  match '/candidates/:id' => "api#candidate"
  match '/districts/:id' => "api#district"
  match '/articles/:id' => "api#article"

  match '/search' => "api#search"
end

如何创建通过API登录的路由(用户使用电子邮件和密码提交请求并接收令牌)?

1 个答案:

答案 0 :(得分:1)

“我如何创建路线”是什么意思?可能你想创建一个类,用一种方法检查返回令牌的电子邮件和密码,例如

class Tokens < ApplicationController

    def create

        @user = User.find_by_email(params[:email])
        # Check for password too!!

        if @user && @user.valid_password?(params[:password])
            render status: 200, json: { token: @user.authentication_token }
        else
          render status: 411, json: { error: "Error message..." }
        end
    end
end

最后添加到您的路线:

post '/tokens' => "tokens#create"

希望它有所帮助。

相关问题