[英]Using devise_token_auth and omniauth-twitter, I can not login with Twitter
發送GET請求到/auth/twitter
,我成功地通過Twitter進行了身份驗證,並重定向到/auth/twitter/callback
。 但是,將GET請求發送到/api/current_user
,api服務器始終返回null
。 而且, user_signed_in?
總是返回false
我不知道如何使用Twitter登錄。 我想獲得current_user
如何使用Twitter登錄? * 版本 :Rails(API模式)5.1.6 ruby 2.4.0 route.rb
Rails.application.routes.draw do
mount_devise_token_auth_for 'User', at: 'auth', controllers: {
omniauth_callbacks: "overrides/omniauth_callbacks",
}
namespace :api, format: 'json' do
root 'posts#index'
get 'current_user', to: 'users#current'
end
end
omniauth_callbacks.rb
module Overrides
class OmniauthCallbacksController < DeviseTokenAuth::OmniauthCallbacksController
def assign_provider_attrs(user, auth_hash)
all_attrs = auth_hash["info"].slice(*user.attributes.keys)
orig_val = ActionController::Parameters.permit_all_parameters
ActionController::Parameters.permit_all_parameters = true
permitted_attrs = ActionController::Parameters.new(all_attrs)
permitted_attrs.permit({})
user.assign_attributes(permitted_attrs)
ActionController::Parameters.permit_all_parameters = orig_val
user
end
end
end
users_controller.rb
class Api::UsersController < ActionController::API
def current
render json: current_user
end
end
您可以嘗試以下解決方案並根據需要對其進行修改
在omniauth_callbacks_controller.rb中,應為以下代碼:
def callback
@user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted?
#your code here to set current_user if necessary
else
#your code here
end
end
def twitter
callback
end
在您的user.rb中應為以下代碼:
def self.from_omniauth(auth)
where(email: auth.info['email'], /add the attributes you want to check/).first_or_create do |user|
user.password = Devise.friendly_token[0,20]
#user.name = auth.info.name # assuming the user model has a name
#user.image = auth.info.image # assuming the user model has an image
end
end
來源: https : //github.com/plataformatec/devise/wiki/OmniAuth :- 概述
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.