【发布时间】:2014-01-25 18:21:52
【问题描述】:
我正在基于 Devise 构建移动 api。
只要我需要 json 响应,我就已经实现了自定义 SessionController 和 RegistrationController:
我的 routes.rb 看起来像:
devise_for(:users, :controllers => { :sessions => "api/sessions", :registrations => "api/registration"})
AFAIK,自上次更新以来,Devise 中的 auth_token 不再使用(3.1.0.rc 下的 CHANGELOG.md)。
这是我的注册控制器:
class Api::RegistrationController < Devise::RegistrationsController
respond_to :json
skip_before_filter :verify_authenticity_token
def create
user = User.new(params[:user])
if user.save
render :json=> {:auth_token=>user.authentication_token, :email=>user.email}, :status=>201
#render :json=> {:success=>true}, :status=>201
return
else
warden.custom_failure!
render :json=> user.errors, :status=>422
end
end
protected
def invalid_login_attempt
render :json=> {:success=>false, :message=>"Error with your login or password"}, :status=>401
end
end
和会话控制器:
class Api::SessionsController < Devise::SessionsController
prepend_before_filter :require_no_authentication, :only => [:create ]
before_filter :ensure_params_exist
respond_to :json
skip_before_filter :verify_authenticity_token
def create
resource = User.find_for_database_authentication(:email => params[:email])
return invalid_login_attempt unless resource
if resource.valid_password?(params[:password])
sign_in("user", resource)
resource.ensure_authentication_token
render :json=> {:success=>true, :auth_token=>resource.authentication_token, :email=>resource.email}
return
end
invalid_login_attempt
end
def destroy
sign_out(resource_name)
end
protected
def ensure_params_exist
return unless params[:email].blank?
render :json=>{:success=>false, :message=>"missing user_login parameter"}, :status=>422
end
def invalid_login_attempt
warden.custom_failure!
render :json=> {:success=>false, :message=>"Error with your login or password"}, :status=>401
end
end
我的用户模型:
class User < ActiveRecord::Base
before_save :ensure_authentication_token
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
def ensure_authentication_token
if authentication_token.blank?
self.authentication_token = generate_authentication_token
end
end
private
def generate_authentication_token
loop do
token = Devise.friendly_token
break token unless User.where(authentication_token: token).first
end
end
end
正如您从上面看到的,我使用this question 来生成我自己的身份验证令牌。不幸的是,在我通过以下查询进行身份验证后
curl -X POST -d 'email=admin111@222example.1111com&password=password' http://192.168.178.89:3000/users/sign_in
我得到一个令牌。但是当我尝试获取受保护的数据时:
curl -X GET -d 'auth_token:UR-Hespxerzorw9UPK9Z' http://192.168.178.89:3000/api/orders.json
我明白了:
{"error":"You need to sign in or sign up before continuing."}
谁能指出我正确的身份验证方式?谢谢!
【问题讨论】:
标签: ruby-on-rails json ruby-on-rails-3 devise