使用Devise进行API身份验证(Ruby on Rails)

9
我正在尝试使用devise配置:token_authenticatable来通过json在我的项目中添加身份验证。
我有sessions_controller#create的可行代码,该代码取自这篇文章-http://blog.codebykat.com/2012/07/23/remote-api-authentication-with-rails-3-using-activeresource-and-devise/
def create
    build_resource
    resource = User.find_for_database_authentication(:email => params[:email])
    return invalid_login_attempt unless resource

    if resource.valid_password?(params[:password])
        resource.ensure_authentication_token!  #make sure the user has a token generated
        render :json => { :authentication_token => resource.authentication_token, :user_id => resource.id }, :status => :created
        return
    end
end

def invalid_login_attempt
    warden.custom_failure!
    render :json => { :errors => ["Invalid email or password."] },  :success => false, :status => :unauthorized
end

问题在于原生的Devise sessions_controller#create看起来是这样的:
  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)
    respond_with resource, :location => after_sign_in_path_for(resource)
  end

我不知道如何将这两种创建方法合并,以使网站和JSON都能正常工作进行身份验证? 更新 可行的代码
def create
    respond_to do |format|

      format.json do
        build_resource
        resource = User.find_for_database_authentication(:email => params[:email])
        return invalid_login_attempt unless resource

        if resource.valid_password?(params[:password])
          resource.ensure_authentication_token!  #make sure the user has a token generated
          render json: { authentication_token: resource.authentication_token, user_id: resource.id }, status: :created
          return
        end
      end

      format.html do
        self.resource = warden.authenticate!(auth_options)
        set_flash_message(:notice, :signed_in) if is_navigational_format?
        sign_in(resource_name, resource)
        respond_with resource, :location => after_sign_in_path_for(resource)
      end

    end
  end

我写了一篇博客文章,介绍了使用Devise的JSON API。这应该会有所帮助:http://jessewolgamott.com/blog/2012/01/19/the-one-with-a-json-api-login-using-devise/ - Jesse Wolgamott
@JesseWolgamott,OP要求提供既支持JSON又支持基于HTML的身份验证解决方案。您的帖子描述了如何实现前者,但未涉及后者。 - Chris Cashwell
1个回答

8
你希望你的SessionsController#create方法看起来像这样:

class Users::SessionsController < Devise::SessionsController
  def create
    resource = warden.authenticate!(scope: resource_name, recall: "#{controller_path}#new")
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)

    respond_to do |format|
      format.html do
        respond_with resource, location: redirect_location(resource_name, resource)
      end
      format.json do
        render json: { response: 'ok', auth_token: current_user.authentication_token }.to_json, status: :ok
      end
    end
  end
end 

确保您已经配置了Devise使用令牌认证密钥,以便您的客户端可以传递。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接