如何在Rails中存储API的密钥?

Tim*_* T. 14 ruby-on-rails

我有几个与我集成的api,需要在我的应用程序的各个部分调用.

存储密钥,用户/密码或令牌信息(例如配置文件)的方法是什么,然后如何调用它们以便在应用程序的其他部分中使用?

谢谢.

ben*_*phw 21

为了使这个问题保持最新,在Rails 4.1中有一种新的方法:

从Rails指南:

Rails 4.1在config文件夹中生成一个新的secrets.yml文件.默认情况下,此文件包含应用程序的secret_key_base,但它也可用于存储其他机密,例如外部API的访问密钥.


sar*_*old 7

您可以在rails已经使用的机制中存储用户名/密码和类似的配置信息; 您可以东东配置数据直接进入您的环境配置文件(其中production,testingdevelopment配置),或者你可以使用自己的机制:

require "yaml"
config_hash = YAML::load_file("/path/to/your/config.yaml")
Run Code Online (Sandbox Code Playgroud)


Lar*_*y K 4

最简单的方法是将信息作为常量存储在各种环境文件中。这样您就可以使用不同的帐户进行开发、生产等。

# Eg
# development/environment.rb
....
API_1_USER = "user101"
API_1_PW = "secret!"
Run Code Online (Sandbox Code Playgroud)

另一种方法是创建一个 yaml 文件,然后在您的应用程序登录 api 时读取它。这是 Rails 本身在 config/databse.yml 文件中使用的样式

添加

您还可以使用散列或嵌套散列存储为常量。

# Eg
# development/environment.rb
....
API_1 = {"user" => "user101", "pw" => "secret!"}
API_2 = {"user" => "user102", "pw" => "double_secret"}

# or nested hashes
API_KEYS = {
             "api_1" => {"user" => "user101", "pw" => "secret!"},
             "api_2" => {"user" => "user102", "pw" => "double_secret"}}

# using them in another file:
foo.signin(API_1['user'], API_1['pw'])
# or
foo.signin(API_KEYS["api_1"]['user'], API_KEYS["api_1"]['pw'])

# note, I use string constants instead of symbols to save vm (since the hash is
# not referenced more than once or twice). You could also use
# symbols as the keys, especially if the hash will be referenced often:
API_1 = {:user => "user101", :pw => "secret!"}
Run Code Online (Sandbox Code Playgroud)