扩展设计 SessionsController 以使用 JSON 进行身份验证 [英] Extending Devise SessionsController to authenticate using JSON
问题描述
我正在尝试为 iPhone 应用程序构建 Rails API.设计适用于通过 Web 界面登录,但我需要能够使用 REST API 创建和销毁会话,并且我想使用 JSON 而不是必须在会话控制器上执行 POST 并且必须解析 HTML 并处理重定向.
I am trying to build a rails API for an iphone app. Devise works fine for logins through the web interface but I need to be able to create and destroy sessions using REST API and I want to use JSON instead of having to do a POST on the sessions controller and having to parse the HTML and deal with a redirect.
我以为我可以这样做:
class Api::V1::SessionsController < Devise::SessionsController
def create
super
end
def destroy
super
end
end
并在 config/routes.rb 中添加:
and in config/routes.rb I added:
namespace :api do
namespace :v1 do
resources :sessions, :only => [:create, :destroy]
end
end
rake 路由显示路由设置正确:
rake routes shows the routes are setup properly:
api_v1_sessions POST /api/v1/sessions(.:format) {:action=>"create", :controller=>"api/v1/sessions"}
api_v1_session DELETE /api/v1/sessions/:id(.:format) {:action=>"destroy", :controller=>"api/v1/sessions"}
当我 POST 到/user/sessions 时一切正常.我得到一些 HTML 和一个 302.
When I POST to /user/sessions everything works fine. I get some HTML and a 302.
现在如果我 POST 到/api/v1/sessions 我得到:
Now if I POST to /api/v1/sessions I get:
未知动作AbstractController::ActionNotFound
Unknown action AbstractController::ActionNotFound
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST http://localhost:3000/api/v1/sessions -d "{'user' : { 'login' : 'test', 'password' : 'foobar'}}"
推荐答案
这终于奏效了.
class Api::V1::SessionsController < Devise::SessionsController
def create
respond_to do |format|
format.html { super }
format.json {
warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
render :status => 200, :json => { :error => "Success" }
}
end
end
def destroy
super
end
end
同时更改routes.rb,记住顺序很重要.
Also change routes.rb, remember the order is important.
devise_for :users, :controllers => { :sessions => "api/v1/sessions" }
devise_scope :user do
namespace :api do
namespace :v1 do
resources :sessions, :only => [:create, :destroy]
end
end
end
resources :users
这篇关于扩展设计 SessionsController 以使用 JSON 进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!