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- 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'
->gotpagethat Iwantedthatneedsauthentication


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_to do|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- X POST '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
post do
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层



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值