Skip to content

Instantly share code, notes, and snippets.

@timothyklim
Created April 26, 2011 06:55
Show Gist options
  • Save timothyklim/941912 to your computer and use it in GitHub Desktop.
Save timothyklim/941912 to your computer and use it in GitHub Desktop.
2-legged OAuth
def authorize
%w{HTTP_AUTHORIZATION X-HTTP_AUTHORIZATION X_HTTP_AUTHORIZATION}.each do |http_header|
@request = request.env[http_header] if request.env[http_header].present?
end
if @request.present?
@oauth_request = OAuth::Helper.parse_header @request
if @oauth_request["oauth_signature_method"] == "HMAC-SHA1"
app = Apps.find(:first, :conditions => {
:consumer_key => @oauth_request["oauth_consumer_key"]} )
if app.present?
consumer = OAuth::Consumer.new(app.consumer_key, app.consumer_secret)
if @oauth_request['oauth_token'].nil?
parameters = { "method" => request.env["REQUEST_METHOD"],
"uri" => request.env["REQUEST_URI"],
"parameters" => @oauth_request }
valid = OAuth::Signature.verify(parameters, { consumer: consumer } )
render text: "#{@oauth_request}\nValid: #{valid}\n"
else
render json: { :errors => "We support only 2-legged OAuth.",
:debug => @oauth_request["oauth_token"] }
end
else
render json: { :errors => "Customer id not found",
:debug => @oauth_request["oauth_consumer_key"] }
end
else
render json: { :errors => "We support only HMAC-SHA1 signature method",
:debug => @oauth_request["oauth_signature_method"] }
end
else
render json: { :errors => "Bad req :(" }
end
end
@timothyklim
Copy link
Author

ruby-1.9.2-p180 :017 > Apps.find(:first)
=> #<Apps _id: 4db5896a6f1dc112f6000001, _type: nil, _id: BSON::ObjectId('4db5896a6f1dc112f6000001'), consumer_key: "632e81447181321baacd7fa05438c64e", consumer_secret: "36e0b22a6c5b8f75797827108f036cbe", app_name: "Yeah">

@timothyklim
Copy link
Author

Apps _id: 4db5896a6f1dc112f6000001, _type: nil, _id: BSON::ObjectId('4db5896a6f1dc112f6000001'), consumer_key: "632e81447181321baacd7fa05438c64e", consumer_secret: "36e0b22a6c5b8f75797827108f036cbe", app_name: "Yeah"

@timothyklim
Copy link
Author

def prepare_access_token(oauth_token, oauth_token_secret)
consumer = OAuth::Consumer.new("632e81447181321baacd7fa05438c64e",
"36e0b22a6c5b8f75797827108f036cbe",
{ :site =>
"http://localhost:9090/oauth/authorize" })

token_hash = { :oauth_token => oauth_token,
:oauth_token_secret => oauth_token_secret }

access_token = OAuth::AccessToken.from_hash(consumer, token_hash )
return access_token
end

access_token = prepare_access_token("", "")
response = access_token.request(:get, "http://localhost:9090/oauth/authorize")

puts response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment