我下面这个优秀的文章,以设置我的Rails的认证部分(3.2)API:
http://blog.joshsoftware.com/2011/12/23/designing-rails-api-using-rabl-and-devise/使用Rails令牌认证,并制定
我做了以下的步骤:
- 新增色器件到的Gemfile
使能的设计为用户模式并运行迁移所需的
- 我的用户模型是
以及数据库中的token_authenticable(通过迁移)。
-Subclassed的这个RegistrationController有:
class RegistrationsController < Devise::RegistrationsController
def new
super
end
def create
resource = warden.authenticate!(:scope => resource_name, :recall => " {controller_path}#new")
sign_in(resource_name, resource)
current_user.reset_authentication_token!
respond_with resource, :location => after_sign_in_path_for(resource)
end
def update
super
end
end
- 在routes.rb中,我有:
devise_for :users, :controllers => {:registrations => "registrations"}
用户创建
我想下面的请求创建一个用户并发回authentification_token:
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"user":{"email":"[email protected]", "password":"pass"}}' 'http://localhost:3000/users.json
我的理解是逻辑应该在注册控制器的“创建”方法中(应该创建用户并同时登录)。我想应该是错的,因为我得到的回报的讯息是:
{"error":"You need to sign in or sign up before continuing."}
什么是缺少的部分,以创建并登录新用户?是不是POST到users.json映射到RegistrationController#create?
USER LOGIN
另外,我想提出以下要求进行登录(送他回到他的authentification_token一旦登录/密码已经被选中)
curl -H "Accept: application/json" -H "Content-type: application/json" -X GET -d '{"user":{"email":"[email protected]","password":"pass"}}' 'http://localhost:3000/users.json
我猜用户逻辑应该在RegistrationController的“更新”方法中进行,但不能100%确定。一旦登录完成,我将添加令牌认证,以保护其他模型的创建/视图。
UPDATE
当我发出:
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"user":{"email":"[email protected]", "password": "mypass", "phone":"1234567890"}}' 'http://localhost:3000/users.json'
我得到了以下信息:
Started POST "/users.json" for 127.0.0.1 at 2012-03-11 20:50:05 +0100
Processing by RegistrationsController#create as JSON
Parameters: {"user"=>{"email"=>"[email protected]", , "password"=>"[FILTERED]", "phone"=>"1234567890"}, "registration"=>{"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]", "phone"=>"1234567890"}, "action"=>"create", "controller"=>"registrations", "format"=>"json"}}
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 1ms
为什么用户不创建并登录,为什么没有authentication_token任何想法返回?
如果您希望在验证之前创建用户,则应添加该代码。设计不这样做。 – 2012-03-11 12:33:17