Created
March 29, 2011 07:50
-
-
Save takeshy/891964 to your computer and use it in GitHub Desktop.
rackベースのoauth signatureチェック
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Rack | |
class SignatureCheck | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
return [ 401,{ 'Content-Type' => 'text/plain','Content-Length' => '0'},[]] unless ::OauthSignature.valid?(env) | |
@app.call(env) | |
end | |
end | |
end | |
class OauthSignature | |
CONSUMER_SECRET = {'stage' =>'????????????' , 'production' => '??????????' } | |
def self.valid?(env) | |
oauth = env["HTTP_AUTHORIZATION"].split(",") | |
raw = [] | |
oauth_token_secret="" | |
oauth_signature ="" | |
oauth.each do |item| | |
e = item.gsub('"','').strip | |
oauth_signature = e.split("=")[1] if e =~ /oauth_signature[^_]/ | |
next if e =~ /OAuth realm|oauth_signature[^_]/ | |
raw.push(e) | |
oauth_token_secret = e.split("=")[1] if e =~ /oauth_token_secret/ | |
end | |
raw += env['QUERY_STRING'].split("&") | |
raw += env['rack.input'].read.split('&') if env['CONTENT_TYPE'] == "application/x-www-form-urlencoded" | |
raw = raw.sort | |
base_str = [env['REQUEST_METHOD'],Rack::Utils.escape("http://"+env["HTTP_HOST"] + env['PATH_INFO']),Rack::Utils.escape(raw.join("&"))].join("&") | |
key = sprintf('%s&',Rack::Utils.escape(CONSUMER_SECRET[Rails.env])) | |
if oauth_token_secret != "" | |
key += Rack::Utils.escape(oauth_token_secret) | |
end | |
Rack::Utils.escape(Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new,key,base_str)).chomp) == oauth_signature | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment