[英]Using devise_token_auth and omniauth-twitter, I can not login with Twitter
Sending GET request to /auth/twitter
, I successfully authenticate with Twitter and redirect to /auth/twitter/callback
. 发送GET请求到
/auth/twitter
,我成功地通过Twitter进行了身份验证,并重定向到/auth/twitter/callback
。 But, sending GET request to /api/current_user
, api server always return null
. 但是,将GET请求发送到
/api/current_user
,api服务器始终返回null
。 And, user_signed_in?
而且,
user_signed_in?
always return false
I can not know how to sign in with Twitter. 总是返回
false
我不知道如何使用Twitter登录。 I want to get current_user
How do I sign in with Twitter? 我想获得
current_user
如何使用Twitter登录? * Version : Rails (API mode) 5.1.6 ruby 2.4.0 routes.rb * 版本 :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 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 users_controller.rb
class Api::UsersController < ActionController::API
def current
render json: current_user
end
end
You can try the following solution and modify it as you want 您可以尝试以下解决方案并根据需要对其进行修改
In your omniauth_callbacks_controller.rb should be the following code: 在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
In your user.rb should be the following code: 在您的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
Source: https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview 来源: https : //github.com/plataformatec/devise/wiki/OmniAuth :- 概述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.