2012-10-01 84 views
5

我正在尝试使用Devise和authenticatable_token构建API以登录到我的Rails应用程序。 我在API模块创建一个SessionsController写下了下面的代码sign_in:用Devise和token_authenticatable登录Rails应用程序:“401未经授权”

module Api 
    module V1 
    class SessionsController < Devise::SessionsController 

     def create 
     resource = warden.authenticate!(scope: resource_name, recall: "#{controller_path}#new") 
     sign_in(resource_name, resource) 
     if current_user 
      if !current_user.authentication_token 
      current_user.reset_authentication_token! 
      end 
      render json: {success: true, auth_token: resource.authentication_token, email: resource.email} 
     else 
      invalid_login_attempt 
     end 
     end 

     protected 

     def invalid_login_attempt 
     warden.custom_failure! 
     render json: {success: false, message: "Error with your login or password"}, status: 401 
     end 
    end 
    end 
end 

的问题是,应用程序提出了401,当我使用的登录,没有任何标记。

RestClient.post "http://localhost:3000/api/v1/users/sign_in", {user: {email: "[email protected]", password: "FILTERED"}}.to_json, :content_type => :json, :accept => :json 

但如果我设置由报名方式它的工作原理提供的令牌:

response_json = RestClient.post "http://localhost:3000/api/v1/users/sign_in?auth_token=#{@token}", {user: {email: "[email protected]", password: "FILTERED"}}.to_json, :content_type => :json, :accept => :json 

那么,为什么呢?执行登录时是否可以禁用令牌认证过程?

回答

3

设计控制器开箱不工作当您使用JSON格式,你就必须做下列之一:

  • 删除内容类型=> JSON和接受=> JSON指令
  • 添加config.navigational_formats = [:HTML,:JSON]你的色器件的配置文件
  • 超载控制器你需要一个特定的反应,这是很常见的处理这种格式

你可以在那里得到一个工作示例http://jessehowarth.com/devise

+0

感谢您的回答。我遵循你网站上的指示,但我仍然得到一个401.此外,我得到了一个错误'未定义的方法'拆分'的500:失败:'resource = warden.authenticate!(:scope => resource_name, :召回=>:失败)'。我也删除了内容类型并接受了我的请求中的指令并添加了navigational_formats。 – obo

+0

其实它是'warden.authenticate!',提高了401. – obo

+0

我终于成功了。我的错误是由错误的路线引起的。我不得不使用localhost:3000/api/v1/sign_in而不是api/v1/users/sign_in。顺便说一句,你的链接和你的建议在配置中帮助我使事情正常工作。 – obo

相关问题