加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 设计令牌身份验证保存Facebook信息

发布时间:2020-12-17 02:08:20 所属栏目:百科 来源:网络整理
导读:我使用 Devise auth token gem和ng-token auth来验证我的单页应用程序.除了使用电子邮件注册外,还可以选择通过Facebook注册.有用. 我的问题是,对于我的Fb请求范围,我设置为获取user_friends,email和public_info,但是当我收到请求时,我没有看到auth_hash requ
我使用 Devise auth token gem和ng-token auth来验证我的单页应用程序.除了使用电子邮件注册外,还可以选择通过Facebook注册.有用.

我的问题是,对于我的Fb请求范围,我设置为获取user_friends,email和public_info,但是当我收到请求时,我没有看到auth_hash request.env [‘omniauth.auth’].这在omniauth-facebook gem documentation中有所描述.

基本上我想保存FB给出的关于我的数据库中用户的内容.你会怎么做?

解决方法

我使用这个终点与Ionic2应用程序,对于Rails 5 API上的Facebook登录请求,使用 Koala和 Devise Token Auth,因此您应该能够在任何Rails 5应用程序上复制:

def facebook
  @graph = Koala::Facebook::API.new(oauth_params[:token],ENV["FACEBOOK_SECRET"])
  @profile = @graph.get_object("me?fields=email,first_name,last_name,picture.type(large)")

  unless @user = User.where(email: @profile["email"])&.first
    @user = User.new(email: @profile["email"])
  end
  #
  # Here you will make your logic for saving Facebook's data on your User model,# customize accordingly
  #
  if @user.new_record?
    p = SecureRandom.urlsafe_base64(nil,false)
    @user.password = p
    @user.password_confirmation = p
    #
    # "Passwordless" login,user must set password after registering,# or be forever haunted by indecipherable SecureRandom value
    #
    @user.name = @profile["first_name"]+ " " + @profile["last_name"]
    @user.remote_avatar_url = @profile["picture"]["data"]["url"]
    @user.confirmed_at = Time.now
    @user.uid = @profile["id"]
    @user.provider = 'Facebook'
  end

  @client_id = SecureRandom.urlsafe_base64(nil,false)
  @token     = SecureRandom.urlsafe_base64(nil,false)
  @user.tokens[@client_id] = {
    token: BCrypt::Password.create(@token),expiry: (Time.now + DeviseTokenAuth.token_lifespan).to_i
  } 
  auth_header = @user.build_auth_header(@token,@client_id)
  # update the response header
  response.headers.merge!(auth_header)
  @user.save!
  if sign_in(:user,@user,store: false,bypass: false)
    render json:  {
      data: @user.token_validation_response 
    }
  end
end

将POST路由指向此并将来自Facebook请求的authResponse.accessToken作为params [:token]传递.Voilà,认证魔术!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读