使用Devise令牌login,是内置的?

所以,我试图使用Devise(版本1.0.3和Rails 2.3.8)来让用户login,但我不完全确定从哪里开始。

http://zyphdesignco.com/blog/simple-auth-token-example-with-devise

上面的教程帮助我打开了令牌function,并展示了如何生成(或删除)令牌……但整个令牌的要点是使用它们来授权用户,对吗?

当我在控制台中查看一个用户时,我可以说user.authentication_token,并得到像“Qm1ne93n_XkgmQTvxDmm”,这是很好,但是我从哪里去?

我尝试使用以下命令行命令击中sign_in根:

curl -d“authentication_token = Qm1ne93n_XkgmQTvxDmm”localhost:3000 / users / sign_in

而且肯定没有成功login。

在会议控制器中,我看到他们称之为:

validation(RESOURCE_NAME)

我所假设的是模块中的某个地方:

包括Devise :: Controllers :: InternalHelpers

哪些被包括,但我不知道在哪里寻找(这绝对不是在源的控制器文件夹)。 如果我可以看看authentication是如何工作的,我可以看看它是否还能看到令牌。

devise让你真的用令牌login,还是只有一个框架来生成它们? 如果它确实让你login他们…你是怎么做到的? 你不能使用curl(即它是否必须在浏览器中?)如果是这样的话,我会推出自己的解决scheme,我需要非浏览器支持。 如果没有,我该如何推出自己的?

我的理解是,您可以使用令牌login或打任意authentication的任意页面,即使使用cURL。 如果你看看config/initializers/devise.rb ,应该有一行代码:

 config.token_authentication_key = :auth_token 

无论token_authentication_key的名称是什么,都应该与请求中的查询或表单参数相匹配。 你在你的例子中使用了authentication_token ,不确定你是否改变了devise.rb来匹配。

如果你想知道事情是如何工作的,我会尝试git clone git://github.com/plataformatec/devise.git并search你需要澄清的方法。

下面是一些示例cURL请求(我做了一个自定义的Users :: SessionsController扩展了Devise :: SessionsController并覆盖了处理JSON的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 

然后我给的cURL请求:

 curl -X POST 'http://localhost:3000/users/sign_in.json' -d 'user[email]=example@example.com&user[password]=password' -> {"response":"ok","auth_token":"ABCDE0123456789"} curl -L 'http://localhost:3000/profile?auth_token=ABCDE0123456789' -> got page that I wanted that needs authentication 

看到这篇文章: http : //www.hyperionreactor.net/blog/token-based-authentication-rails-3-and-rails-2

基本上所有你需要的是追加令牌到你的请求,你会自动validation,即localhost:3000 / posts.xml?auth_token = the_token

对我来说这是一个很好的起点:

迁移到添加authentication_token

 class AddTokenBasedAuthentication < ActiveRecord::Migration def change add_column :users, :authentication_token, :string add_index :users, :authentication_token, unique: true end end 

然后在应用程序控制器中:

 class ApplicationController < ActionController::Base before_filter :authenticate_user_from_token! before_action :authenticate_user!, except: <your login GET action> private def authenticate_user_from_token! email = params[:email].presence user = email && User.find_by(email: email) sign_in user if user && Devise.secure_compare(user.authentication_token, params[:auth_token]) end end 

然后链接build设是正义的

 www.yoursite.com/?email=the@email.address&auth_token=whatever_auth_token_is_stored_for_that_user 

来源: 这个要点来自devise的wiki , 这个教程 (上面提到)