以下简要介绍我目前的认证流程:
>用户在移动客户端,客户端上选择“用Facebook登录”
重定向到Facebook应用程序并请求access_token
>成功后,Facebook使用访问令牌和客户端进行回复
重定向到我的应用程序
>客户端将访问令牌发送到我的API
>我的API使用koala gem来检查访问令牌是否有效.
>如果令牌有效,Facebook将用户数据发送到API
创建新用户的位置.如果用户已经存在,我的API会发送用户数据.
我的API在步骤4中处理访问令牌,如下所示:
def self.authenticate_user_from_facebook(fb_access_token)
user = User.new
graph = Koala::Facebook::API.new(fb_access_token)
profile = graph.get_object('me')
#user['fb_id'] = profile['id']
#user['fb_token'] = fb_access_token
# Generate user hash
uhash = Hash.new
uhash['provider'] = 'facebook'
uhash['uid'] = profile['id']
uhash['info'] = Hash.new
uhash['info']['nickname'] = profile['username']
uhash['info']['name'] = profile['name']
uhash['info']['email'] = profile['email']
uhash['info']['first_name'] = profile['first_name']
uhash['info']['last_name'] = profile['last_name']
uhash['info']['verified'] = profile['verified']
uhash['info']['urls'] = Hash.new
uhash['info']['urls']['Facebook'] = profile['link']
uhash['credentials'] = Hash.new
uhash['credentials']['token'] = fb_access_token
uhash['extra'] = Hash.new
uhash['extra']['raw_info'] = Hash.new
#Save the new data
user = User.apply_auth(uhash)
return user
end
def self.apply_auth(uhash)
User.where(:uid => uhash['uid'],:provider => uhash['provider']).first_or_create do |user|
user.provider = uhash['provider']
user.uid = uhash['uid']
user.nickname = uhash['info']['nickname']
user.email = uhash['info']['email']
user.name = uhash['info']['name']
user.first_name = uhash['info']['first_name']
user.last_name = uhash['info']['last_name']
end
end
创建用户后,他们可以使用其访问令牌向我的API发出请求,如下所示:
在步骤2中,API正在使用koala来验证用户访问令牌.这通过将以下before_filter应用于所有控制器来完成.
before_filter :current_user
在我的application_helper.rb中
def current_user
@current_user ||= User.authenticate_user_from_facebook(params[:access_token])
end
每当用户向我的API发出请求时,使用koala gem来检查令牌是否有效,然后处理该请求.
我现在要添加的是仅使用用户名和密码的身份验证.
我研究的事情
我一直在不断地提到Railscast 235,209,250,82,并在OAuth2上阅读.我对认证工作原理有一个基本的了解,但是我无法将其应用到我目前的认证流程中.
设计令牌认证
参考Railscast 235,209和这个博文:
http://matteomelani.wordpress.com/2011/10/17/authentication-for-mobile-devices/
我可以了解如何登录并验证用户名和密码登录的用户.不过我很困惑,如何将与我的Facebook登录流网络.我不明白如何为已经拥有Facebook生成的访问令牌的用户创建一个会话.
的OAuth2
使我的API成为一个OAuth2提供商似乎是一个很好的方法,但它似乎有点愚蠢的重定向到浏览器,我不知道是否可能从浏览器重定向到我的应用程序.
认证从头开始
这是我正在考虑的选择,但我会重新发明.
感谢您阅读这篇文章!任何建议是赞赏!
解决方法
这是RailsCast on Warden.(需要Pro订阅)