如何在Devise + Omniauth-facebook + Devise_token_auth上使用facebook访问令牌?
有没有办法将访问令牌以某种方式挂钩到omniauth-facebook并让用户注册/登录?或欢迎任何其他解决方案。
我可以在移动端从facebook图形API获取访问令牌。
我试图将访问令牌放在回调网址上: / omniauth /实/回调?代码= ACCESS_TOKEN 但它只是返回 {“errors”:[“使用POST / sign_in登录。不支持GET。”]}
我看过:
Rails API: Authenticate users from native mobile apps using username/password or facebook token
建议看看Warden的解决方案,但我不认为它需要这么复杂。
omniauth for rails and ios authentication
建议的解决方案是宝石,但不再维护宝石。
Rails Devise OmniAuth Facebook Login from iOS
建议的解决方案影响了移动端的开发,我希望不会这样做。
答案 0 :(得分:1)
我决定尝试一下它似乎有效。
我从@JeremyMoyers here获取了代码。它确实是一个临时解决方案,但似乎可以解决这个问题。
我已经覆盖了omniauth_success的DeviseTokenAuth控制器操作:
路线:
config/routes.rb
namespace :api do
scope :v1 do
# mount_devise_token_auth_for 'User', at: 'auth'
mount_devise_token_auth_for 'User', at: 'auth', controllers: {
omniauth_callbacks: 'omniauth_callbacks',
}
end
end
控制器:
app/controllers/omniauth_callbacks_controller.rb
class OmniauthCallbacksController < DeviseTokenAuth::OmniauthCallbacksController
def omniauth_success
# get_resource_from_auth_hash
# Remove original get_resource_from_auth_hash and implement custom get_resource
get_resource_from_uhash(params[:access_token],params[:expires_in])
create_token_info
set_token_on_resource
create_auth_params
# Skip confirmation is done at custom get_resource
# if resource_class.devise_modules.include?(:confirmable)
# don't send confirmation email!!!
# @resource.skip_confirmation!
# end
sign_in(:user, @resource, store: false, bypass: false)
if @resource.save!
update_auth_header
yield @resource if block_given?
redirect_to @resource
# render_data_or_redirect('deliverCredentials', @auth_params.as_json, @resource.as_json)
else
redirect_to rooth_path
end
end
protected
def get_resource_from_uhash(access_token, expires_in)
graph = Koala::Facebook::API.new(access_token)
profile = graph.get_object('me?fields=email,name,id,picture')
# logger.info(profile)
@resource = User.where({
uid: profile['id'],
provider: 'facebook'
}).first_or_initialize do |user|
user.provider = 'facebook'
user.uid = profile['id']
user.name = profile['name']
user.oauth_token = access_token
user.password = Devise.friendly_token[0,20]
user.image = profile['picture'] if profile['picture'].present?
user.oauth_expires_at = Time.at(expires_in)
user.skip_confirmation!
user.save!
end
if @resource.new_record?
@oauth_registration = true
set_random_password
end
@resource
end
end
如果有任何安全问题请与我联系。