Created
May 17, 2018 08:56
-
-
Save coderliu/09ff33461f9db74f2ac3bb421b176857 to your computer and use it in GitHub Desktop.
a ActiveSupport Concern for Aliyun OSS callback to save your time
This file contains 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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
[project_root]/app/controllers/concerns
include AliyunOssCallbackable
to your controllerbefore_action :authenticate_aliyun!, only: :callback
to your controller, replace:callback
with your callback action name if it is not:callback