A "central place" where to definitely set the SSL certificate variable
I am using Ruby on Rails 3 and I would like to have a "central place" where to definitely set the SSL certificate to use inside my application.
Almost everywhere in code I have HTTPS requests like this
e = Typhoeus::Request.get("https://example.com/action",
:ssl_cacert => "ca_file.cer",
:ssl_cert => "acert.c开发者_JS百科rt",
:ssl_key => "akey.key",
[...]
end
So, in order to specify a SSL certificate for all my request, I would like to set a global variable (I heard that global variable can be dangerous...) or something like that in a safe way.
You could build a SSL helper class, and use that (I'd put it in lib, but that's mostly just user preference):
class MySSL
SSL_DEFAULTS = {
:ssl_cacert => 'ca_cert.cer',
:ssl_cery => 'acert.crt',
:ssl_key => 'akey.key'
}
def self.get(uri, options = {})
options.reverse_merge!(SSL_DEFAULTS)
Typhoeus::Request.get(uri, options)
end
# And so forth for post, etc.
end
Where reverse_merge! is a convenient Rails extension to give default options for a hash (if the original hash has those keys already, they won't be overwritten). You avoid setting a global variable, too, by using a class constant. And in the rest of your code, you're able to call
MySSL.get('https://example.com/action')
or
MySSL.get('https://example.com/action', :other => :options)
which are a lot cleaner, in comparison.
Hope this helps!
You can use OpenSSL::SSL::SSLContext::DEFAULT_CERT_STORE
methods #add_file
and #add_path
to set it on the default cert store; this will get picked up by pretty much everything that doesn't override it, in particular Net::HTTP. I'm not sure about Typhoeus, but it should work as long as it doesn't change it.
精彩评论