Skip to content

Instantly share code, notes, and snippets.

@coderliu
Created May 17, 2018 08:56
Show Gist options
  • Save coderliu/09ff33461f9db74f2ac3bb421b176857 to your computer and use it in GitHub Desktop.
Save coderliu/09ff33461f9db74f2ac3bb421b176857 to your computer and use it in GitHub Desktop.
a ActiveSupport Concern for Aliyun OSS callback to save your time
module AliyunOssCallbackable
extend ActiveSupport::Concern
PUB_KEY_URL_PREFIX = 'http://gosspublic.alicdn.com/'
PUB_KEY_URL_PREFIX_S = 'https://gosspublic.alicdn.com/'
def authenticate_aliyun!
pub_key_url = Base64.decode64(request.headers['x-oss-pub-key-url'])
pub_key = get_public_key(pub_key_url)
rsa = OpenSSL::PKey::RSA.new(pub_key)
authorization = Base64.decode64(request.headers['authorization'])
req_body = request.body.read
auth_str = if request.query_string.empty?
"#{CGI.unescape(request.path)}\n#{req_body}"
else
"#{CGI.unescape(request.path)}?#{request.query_string}\n#{req_body}"
end
unless rsa.public_key.verify(OpenSSL::Digest::MD5.new, authorization, auth_str)
head :unauthorized
return
end
end
def get_public_key(pub_key_url, reload = false)
unless pub_key_url.start_with?(PUB_KEY_URL_PREFIX) ||
pub_key_url.start_with?(PUB_KEY_URL_PREFIX_S)
head :unauthorized
return
end
if reload || @pub_key.nil?
@pub_key = open(pub_key_url) { |f| f.read }
end
@pub_key
end
end
@coderliu
Copy link
Author

coderliu commented May 17, 2018

Usage:

  1. add this file to your [project_root]/app/controllers/concerns
  2. add include AliyunOssCallbackable to your controller
  3. add before_action :authenticate_aliyun!, only: :callback to your controller, replace :callback with your callback action name if it is not :callback

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