2013-11-02 54 views
5

使用oauth2寶石嘗試將OAuth轉換爲Ruby時,我總是收到{"error" : 401}。維基頁面表示,這是因爲不正確或不存在的憑據,但我敢肯定我有正確的:使用OAuth與Reddit時獲取401錯誤代碼

require "oauth2" 
require "base64" 

reddit = OAuth2::Client.new ENV["API_ID"], ENV["API_SECRET"], \ 
    :authorize_url => "https://ssl.reddit.com/api/v1/authorize", 
    :token_url  => "https://ssl.reddit.com/api/v1/access_token", 
    :site   => "https://oauth.reddit.com/api/v1/" 

state = Digest::SHA1.hexdigest rand(36**8).to_s(36) 
redirect_uri = "http://localhost:8080/oauth2/callback" 

params = {"scope" => "identity", 
      "response_type" => "code", 
      "redirect_uri" => redirect_uri, 
      "state" => state, 
      "duration" => "permanent" 
     } 

puts reddit.auth_code.authorize_url params 

# Get the url with the code that reddit redirects to 
redir = gets.chomp.strip 
code = redir.match(/code=([^&]*)/).captures 
returned_state = redir.match(/state=([^&]*)/).captures 
raise "State does not Match!" unless state === returned_state[0] 

params = {"scope" => "identity", 
      "redirect_uri" => redirect_uri, 
      "state" => state 
     } 

token = reddit.auth_code.get_token(code[0], params, :headers => {'Authorization' => "Basic " + Base64.strict_encode64('#{ENV["API_ID"]}:#{ENV["API_SECRET"]}')}) 
response = token.get('me') 
puts response 

回答

0

已經有一段時間了,代碼已經消失了一段時間,所以現在無法診斷它。我的猜測是要處理reddit的OAuth2框架相當鬆散的實現。不過,如果您使用的是Ruby並希望通過OAuth2連接到reddit,那麼您可能更願意看看redd