【问题标题】:Extending devise to support a JSON API扩展设计以支持 JSON API
【发布时间】:2012-12-14 16:15:43
【问题描述】:

我们正在升级具有两种用户身份验证方式的应用程序。

  1. 具有before_filter :authenticate_user! 回调并像标准 Rails 站点一样访问的控制器。
  2. API 模块内的控制器,由客户端应用程序通过 JSON 访问。除了仅具有前缀 /api 的身份验证操作之外,所有路由都具有前缀 /api/session_id/

两种方式都使用User 模型对用户进行身份验证。

有没有办法配置设计来支持它们?怎么样?

注意:我不想通过 JSON 创建用户。我只是想对他们进行身份验证。

【问题讨论】:

    标签: ruby-on-rails ruby devise


    【解决方案1】:

    我通过覆盖设计的会话控制器来做到这一点。

    为自定义会话控制器添加路由条目:

     devise_for :users, :controllers => {:sessions => 'sessions'}
    

    并覆盖会话控制器:

      class SessionsController < Devise::SessionsController
    
        def create
          resource = warden.authenticate!(:scope => resource_name, :recall => "sessions#failure")
          return sign_in_and_redirect(resource_name, resource)
        end
    
        def sign_in_and_redirect(resource_or_scope, resource=nil)
          scope = Devise::Mapping.find_scope!(resource_or_scope)
          resource ||= resource_or_scope
          sign_in(scope, resource) unless warden.user(scope) == resource
          respond_with do |format|
            format.json  {render :json => {:success => true} }
            format.any  {super}
          end
        end
    
        def failure
          respond_with do |format|
            format.json  {render:json => {:success => false, :errors => ["Login failed."]} }
            format.any  {redirect_to :back, :notice => "Wrong Email / Password" }
          end
          #return render:json => {:success => false, :errors => ["Login failed."]}
        end
    
      end
    

    "Rails & Devise: Override SessionsController 是同一主题的更多讨论。

    【讨论】:

    • 如何使用 post 路由 /api/authenticate 对用户进行身份验证?
    • 添加路由,devise_for :users do post "/api/authenticate" => "devise/sessions#create" end
    【解决方案2】:

    creating a new stategy to warden结束。

    valid? 方法中,我检查 params[:controller] 是否来自 api 命名空间。 这样我就没有通过http接触默认的设计认证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 2012-02-15
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2013-08-20
      • 2018-04-12
      相关资源
      最近更新 更多