`
duoerbasilu
  • 浏览: 1482267 次
文章分类
社区版块
存档分类
最新评论

devise中如何使用auth_token认证 与 RubyChina api认证的区别

 
阅读更多
1.修改配置文件config/initializers/devise.rb

config.token_authentication_key=:auth_token

2.修改controlleraction

classUsers::SessionsController<Devise::SessionsController
defcreate
resource=warden.authenticate!(:scope=>resource_name,:recall=>"#{controller_path}#new")
set_flash_message(:notice,:signed_in)ifis_navigational_format?
sign_in(resource_name,resource)

respond_todo|format|
format.htmldo
respond_withresource,:location=>redirect_location(resource_name,resource)
end
format.jsondo
render:json=>{:response=>'ok',:auth_token=>current_user.authentication_token}.to_json,:status=>:ok
end
end
end
end

3,可以使用如下的命令测试

curl-XPOST'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'
->gotpagethatIwantedthatneedsauthentication


devise 提供的auth token 方式不是很合适,需要修改devise.rb配置文件,与web认证冲突
还是RubyChina实现的比较好一点

Ruby-China的代码中如何实现tokenauthentication登录
1,登录的时候生成private_token代码

#用户密钥,用于客户端验证
field:private_token

#重新生成PrivateToken
defupdate_private_token
random_key="#{SecureRandom.hex(10)}:#{self.id}"
self.update_attribute(:private_token,random_key)
end


2,在客户端登录的时候,返回private_token

defcreate
resource=warden.authenticate!(:scope=>resource_name,:recall=>"#{controller_path}#new")
set_flash_message(:notice,:signed_in)ifis_navigational_format?
sign_in(resource_name,resource)
respond_todo|format|
format.html{redirect_toafter_sign_in_path_for(resource)}
format.json{render:status=>'201',:json=>resource.as_json(:only=>[:login,:email,:private_token])}
end
end

3,可以使用如下命令测试
curl-XPOST'http://ruby-china.org/account/sign_in.json'-d"user[login]=xxxx&user[password]=xxxxxx"

4,如何在下次接口定义中使用?
#filepath:lib/api.rb
#
#Postanewtopic
#requireauthentication
#params:
#title
#body
#node_id
postdo
authenticate!
@topic=current_user.topics.new(:title=>params[:title],:body=>params[:body])
@topic.node_id=params[:node_id]
@topic.save!
#TODOerrorhandling
end
5,authenticate!的源代码【在lib/api/helper.rb文件中】
#userhelpers
defcurrent_user
@current_user||=User.where(:private_token=>params[:token]||'').first
end

defauthenticate!
error!({"error"=>"401Unauthorized"},401)unlesscurrent_user
end
RubyChina没有使用Devise默认的认证码,定义了一套新的认证机制,结合Grape做接口,与web层



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics