【发布时间】:2013-09-30 11:39:53
【问题描述】:
所以我这几天一直在努力想弄清楚如何将用户名/密码身份验证添加到我的 Rails 移动 API。
以下是我当前身份验证流程的简要概述:
用户在移动客户端选择“使用 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 提供者似乎是一个好方法,但重定向到浏览器似乎有点傻,我不知道是否可以从浏览器重定向回我的应用程序。
从头开始验证 这是我正在考虑使用的选项,但我会重新发明轮子。
感谢您阅读这篇长文!任何建议表示赞赏!
【问题讨论】:
-
那么你最终是如何解决这个问题的?
-
最后..你用什么方法?
-
这些图表正是我过去几个月一直在想的。您的搜索有什么更新吗?
标签: ios api rest oauth-2.0 omniauth