ruby的omniauth gem包

来源:互联网 发布:p2c网络金融平台 编辑:程序博客网 时间:2024/06/06 00:53

写了几天第三方登录的程序,之前没用gem包,都是按照auth2的步骤来取登录信息(先取code再取token再根据token取用户信息),写了一堆的代码,看了各个第三方的api,花了很多很多时间。。。

今天发现这些都是做无用功,几乎所有常用的第三方平台都有相应的gem包


1.gemfile
gem 'omniauth'
gem 'omniauth_mm', path: 'omniauth_mm'  #自己写得,与app同级目录下
gem 'omniauth-facebook'
gem 'omniauth-twitter'
gem 'omniauth-googleplus'

gem 'omniauth-line'


2.config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, Constants::CONFIG["facebook_clientid"], Constants::CONFIG["facebook_secret"]
  provider :twitter, Constants::CONFIG["twitter_key"], Constants::CONFIG["twitter_secret"]
  provider :googleplus, Constants::CONFIG["google_id"], Constants::CONFIG["google_secret"]
  provider :mm, Constants::CONFIG["mm_application_id"], Constants::CONFIG["mm_secret"]
end


3. config\routes.rb

#将omniauth的callback映射到自己的action

  get '/auth/facebook/callback', to: 'third_party#auth_facebook_ok'
  get '/auth/twitter/callback', to: 'third_party#auth_twitter_ok'
  get '/auth/googleplus/callback', to: 'third_party#auth_google_ok'
  get '/auth/line/callback', to: 'third_party#auth_line_ok'
  get '/auth/mm/callback', to: 'third_party#auth_mm_ok'


4.自己的action取授权成功后的信息

#twitter授权登录成功后
  def auth_twitter_ok
    userInfo = request.env['omniauth.auth']["info"]
    userName = userInfo["name"]
    userId = request.env['omniauth.auth']["uid"]
    picUrl = userInfo["image"]
    return redirect_to "/"
  end

0 0