2016-07-07 137 views
1

使用「的oauth2」寶石和Heroku的服務器,我已經成功地創建一個客戶端對象,並把用戶重定向到登錄網站:回調在Ruby on Rails的

client = OAuth2::Client.new(
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 
:authorize_url => "/oauth/authorize", 
:token_url => "/oauth/token", 
:site => "https://connect.xxxxxxxxxx.com") 

redirect_to(client.auth_code.authorize_url(:redirect_uri => 'https://xxxxx.herokuapp.com/callback')) 

瀏覽器之後自身重定向到如預期回調的鏈接,是這樣的:

https://xxxxx.herokuapp.com/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 

我需要訪問的授權碼,然後發送的訪問令牌POST請求和刷新令牌,但作爲全新到Ruby和Ruby on Rails,我不是確定如何獲取回調並解析代碼。所有我研究過的十幾篇教程/文檔都提到授權代碼應該「神奇地獲得」,但我不確定它是如何明確地工作的。我試圖創建一個'回調'控制器和視圖無濟於事 - 有可能丟失的路線文件中的東西?非常感謝幫助!

回答

0

你CallbackController會開始看起來像這樣也許:

class CallbackController < ApplicationController 
    def index 
    access_token = client.auth_code.get_token(params[:code], redirect_uri: 'https://xxxxx.herokuapp.com/callback') 
    # Now you have an OAuth2::AccessToken object that you can either use to: 
    # - make direct requests to the API 
    # - or access access_token.token, access_token.refresh_token, access_token.expires_at, access_token.expires_in and store those 
    # somewhere for later use 
    # http://www.rubydoc.info/github/intridea/oauth2/OAuth2/AccessToken 
    end 

    private 

    def client 
    @client ||= OAuth2::Client.new(
     "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 
     "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 
     authorize_url: "/oauth/authorize", 
     token_url: "/oauth/token", 
     site: "https://connect.xxxxxxxxxx.com" 
    ) 
    end 
end