[英]Rails API: Authenticate users from native mobile apps using username/password or facebook token
所以我現在已經把頭發拉了幾天,試圖弄清楚如何在我的rails mobile 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提供商似乎是一個很好的方法,但重定向到瀏覽器似乎有點愚蠢,我不知道是否可以從瀏覽器重定向到我的應用程序。
從頭開始驗證這是我想要的選擇,但我會重新發明輪子。
感謝您閱讀這篇長篇文章! 任何建議表示贊賞!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.