我下面這個優秀的文章,以設置我的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