1.Gemfile 内添加如下 gem,并执行 bundle
gem "omniauth-oauth2"
gem "omniauth-weibo-oauth2"
2.(a) 添加了专门做第三方服务的 yml 文件,/confg/services.yml
common: &common
weibo:
api_key: "申请的key"
api_secret: "申请的secret"
redirect_uri: "http://127.0.0.1/users/auth/weibo/callback"
production:
<<: *common
development:
<<: *common
test:
<<: *common
2.(b) 同时在 devise.rb 中这么写
SERVICES = YAML.load_file(Rails.root.join("config", "services.yml")).fetch(Rails.env)
Devise.setup do |config|
config.omniauth :weibo, SERVICES['weibo']['api_key'], SERVICES['weibo']['api_secret']
end
3.由于用的 devise,所以 user.rb 做了如下更改
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
# devise :database_authenticatable, :registerable,
# :recoverable, :rememberable, :trackable, :validatable
devise :database_authenticatable, :registerable,
:recoverable,:rememberable,:validatable,
:omniauthable, :omniauth_providers => [:weibo]
has_many :orders
end
4.以下是 devise 的 OmiauthCallbackController 的 code
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
# You should configure your model like this:
devise :omniauthable, omniauth_providers: [:weibo]
def weibo
omniauth_process
end
protected
def omniauth_process
omniauth = request.env['omniauth.auth']
authentication = Authentication.where(provider: omniauth.provider, uid: omniauth.uid.to_s).first
if authentication
set_flash_message(:notice, :signed_in)
sign_in(:user, authentication.user)
redirect_to root_path
elsif current_user
authentication = Authentication.create_from_hash(current_user.id, omniauth)
set_flash_message(:notice, :add_provider_success)
redirect_to authentications_path
else
session[:omniauth] = omniauth.except("extra")
set_flash_message(:notice, :fill_your_email)
redirect_to new_user_registration_url
end
end
def after_omniauth_failure_path_for(scope)
new_user_registration_path
end
end
5.看看 rake routes 的结果
user_weibo_omniauth_authorize GET|POST /users/auth/weibo(.:format) devise/omniauth_callbacks#passthru
user_weibo_omniauth_callback GET|POST /users/auth/weibo/callback(.:format) devise/omniauth_callbacks#weibo
6.open.weibo.com 中的配置
回调 redirect uirl 设置如下
7.微博登录后,合理的出现了授权界面,但是点击了授权后,没有达到理想的效果,返回如下 json error。
Started GET "/users/auth/weibo/callback?state=27f67b398054bd6d3e3d8f7ef6d65064c4b87d986784a7c8&code=[FILTERED]" for 127.0.0.1 at 2016-10-31 22:15:59 +0800
I, [2016-10-31T22:15:59.933569 #40827] INFO -- omniauth: (weibo) Callback phase initiated.
E, [2016-10-31T22:15:59.991661 #40827] ERROR -- omniauth: (weibo) Authentication failure! invalid_credentials: OAuth2::Error, invalid_request: miss redirect uri.
{"error":"invalid_request","error_code":21323,"request":"/oauth2/access_token","error_uri":"/oauth2/access_token","error_description":"miss redirect uri."}
总结下,我除了应用的介绍图片没有完善,其他的设置都按照标准的设置走的,为什么 callback 的时候还说我 miss redirect uri?