【问题标题】:Devise API authentication [closed]设计 API 身份验证 [关闭]
【发布时间】:2011-11-28 17:04:38
【问题描述】:

我正在开发一个 Rails Web 应用程序,它还为移动设备提供基于 JSON 的 API。移动客户端应首先通过 (email/pass) 获取令牌,然后客户端将使用该令牌进行后续 API 调用。

我是 Devise 的新手,我正在寻找一个类似于 authenticate(email, pass) 的 Devise API 并期望它返回 true/false,然后基于此我将创建并交回令牌或返回拒绝消息.但似乎 Devise 没有提供这样的功能。

我知道 Devise 1.3 提供基于 JSON 的身份验证,但这与我需要的有点不同 - 我需要生成令牌并处理回客户端,然后使用令牌完成身份验证。

有人可以指点一下吗?

【问题讨论】:

  • 这是一个很好的问题,不幸的是答案已经过时了。我们需要 Rails 4 的新答案。我希望它能够尽快运行 :)

标签: ruby-on-rails ruby json api devise


【解决方案1】:

有一个名为:token_authenticatable 的设计配置。因此,如果您将其添加到“用户”中的设计方法中,那么您只需调用即可在 API 中进行身份验证

"/api/v1/recipes?qs=sweet&auth_token=[@user.auth_token]"

您可能也希望在您的用户中使用它:

before_save :ensure_authentication_token

更新(带有 API 授权码)

您正在寻找的方法是:

resource = User.find_for_database_authentication(:login=>params[:user_login][:login])
resource.valid_password?(params[:user_login][:password])

这是我的gist with a full scale JSON/API login with devise

【讨论】:

  • 谢谢 Jesse,我的问题实际上与令牌本身无关,而是关于如何从移动设备以 JSON 格式进行自定义电子邮件/传递身份验证,以获取令牌。
  • 再次感谢杰西,正是我想要的
  • 我得到了valid_password?未定义的方法错误。我假设 valid_password 是 Devise 中的一种方法,我不需要实现它
  • 对查看此内容的人的更新,:token_authenticatable 现在已弃用。
  • 如果您在 2013 年 11 月之后到达这里,您需要知道 Authenticable 已从 Devise 中删除,因此此解决方案可能无法正常工作。看看这个:github.com/plataformatec/devise/wiki/…
【解决方案2】:

我建议通读 Devise Wiki,因为 Devise 本身就支持令牌身份验证作为其模块之一。我没有亲自在 Devise 中使用过令牌身份验证,但 Brandon Martin 有一个示例令牌身份验证示例 here

【讨论】:

  • 谢谢,但是我的问题是如何使用电子邮件/密码进行身份验证以获取令牌,而这需要使用 JSON 进行,我不能让用户在移动设备上键入令牌。
  • 示例链接已损坏
【解决方案3】:

Devise 基于 Warden,一个 Rack 的身份验证中间件。

如果您需要实现自己的(替代)方式来验证用户身份,您应该结合 Devise 附带的策略查看 Warden:https://github.com/plataformatec/devise/tree/master/lib/devise/strategies

【讨论】:

    【解决方案4】:

    如果令牌验证不是您想要做的,您还可以返回一个 cookie 并让客户端在请求标头中包含该 cookie。它的工作方式与 Web 会话控制器非常相似。

    在 API 会话控制器中

    class Api::V1::SessionsController < Devise::SessionsController
    
      skip_before_action :authenticate_user!
      skip_before_action :verify_authenticity_token
    
      def create
        warden.authenticate!(:scope => :user)
        render :json => current_user
      end
    
    end
    

    在路线中

    namespace :api, :defaults => { :format => 'json' } do
      namespace :v1 do
        resource :account, :only => :show
        devise_scope :user do
          post :sessions, :to => 'sessions#create'
          delete :session, :to => 'sessions#destroy'
        end
      end
    end
    

    那么你就可以做这种事情了(例子是使用HTTPie

    http -f POST localhost:3000/api/v1/sessions user[email]=user@email.com user[password]=passw0rd
    

    响应标头将在 Set-Cookie 标头中有一个会话。将 this 的值放入后续请求中。

    http localhost:3000/api/v1/restricted_things/1 'Cookie:_my_site_session=<sessionstring>; path=/; HttpOnly'
    

    【讨论】:

      猜你喜欢
      • 2012-02-09
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      相关资源
      最近更新 更多