2012-11-29 141 views
3

我有一个带有Rails后端的PhoneGap应用程序。我试图找出使用json从移动应用程序认证用户的最佳方式。PhoneGap Mobile Rails身份验证(从零开始设计?身份验证?)

我目前使用设计,,但我不必使用。什么是最简单的方法来修改设计与Phonegap中的移动应用程序一起工作?

我知道这里有不少帖子......但是,其中一些已经过时或看起来像非常复杂的黑客。希望可以从一些经过测试的项目或教程中获得更多的最新信息。

我发现的一个帖子也建议使用jsonp,但它也看起来像一个非常复杂的黑客。你可以在这里找到它:http://vimeo.com/18763953

我也想知道,如果我只想过得更好与认证从头开始了,在这个Railscast布局:http://railscasts.com/episodes/250-authentication-from-scratch

谢谢!

回答

12

您应该重写设备的sessionsregistrations控制器。我只会告诉你如何覆盖会话控制器:

首先,转到你的用户模型并添加令牌认证模块。事情是这样的:

devise :token_authenticatable 

before_save :ensure_authentication_token 

然后编辑devise.rb文件来配置该模块:

# You can skip storage for :http_auth and :token_auth by adding those symbols to the array below. 
config.skip_session_storage = [:token_auth] 

# Defines name of the authentication token params key 
config.token_authentication_key = :auth_token 

现在编辑您的路线和点到新的控制器:

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

然后像这样创建你的控制器:

class SessionsController < Devise::SessionsController 
    def create 
    respond_to do |format| 
     format.html { 
     super 
     } 
     format.json { 
     build_resource 
     user = User.find_for_database_authentication(:email => params[:user][:email]) 
     return invalid_login_attempt unless resource 

     if user.valid_password?(params[:user][:password]) 
      render :json => { :auth_token => user.authentication_token }, success: true, status: :created 
     else 
      invalid_login_attempt 
     end 
     } 
    end 
    end 

    def destroy 
    respond_to do |format| 
     format.html { 
     super 
     } 
     format.json { 
     user = User.find_by_authentication_token(params[:auth_token]) 
     if user 
      user.reset_authentication_token! 
      render :json => { :message => 'Session deleted.' }, :success => true, :status => 204 
     else 
      render :json => { :message => 'Invalid token.' }, :status => 404 
     end 
     } 
    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 

设计has a page about this,但它只指向一些已经过时的指南。但也许它会帮助你。

+0

+1谢谢你。你知道关于在移动端存储会话吗?我听说phonegap没有cookies,所以这意味着我不得不使用localStorage存储cookie,然后以某种方式发布每个请求? – botbot

+1

btw @Ashitaka,你说的对,那些文档有点过时。我真的很惊讶这种设置没有更多的文档记录,因为移动应用程序和轨道似乎是近来的趋势。 – botbot

+1

只需搜索本地存储,它非常容易。在您的Phonegap应用程序中,登录时,对会话url进行ajax调用(您可以使用'rake routes'找到它),然后使用以下内容存储该令牌:'localStorage.setItem('auth_token',authentication_token);'。然后你可以用'localStorage.getItem('auth_token')'检索它。 – Ashitaka