简体   繁体   English

如何使用 Rails Secrets 存储 Google API 凭据?

[英]How can I store Google API Credentials using Rails Secrets?

This question is similar to How can I authorize a Google Service Account without the default credentials file?此问题类似于如何在没有默认凭据文件的情况下授权 Google 服务帐户? but specifically about how to use Rails' built in secrets/credentials functionality.但特别是关于如何使用 Rails 内置的秘密/凭证功能。

I realise it needs to be JSON but when I store credentials in a private method and pass that method to json_key_io I get a NoMethodError :我意识到它需要是 JSON 但是当我将凭据存储在私有方法中并将该方法传递给json_key_io我得到一个NoMethodError

def call
  auth = Google::Auth::ServiceAccountCredentials.make_creds(
    json_key_io: credentials,
    scope: Google::Apis::ClassroomV1::AUTH_CLASSROOM_ROSTERS
  )
end

private

  def credentials
    @credentials ||= {
      type: "service_account",
      project_id: Rails.application.credentials.google[:project_id],
      private_key_id: Rails.application.credentials.google[:private_key_id],
      private_key: Rails.application.credentials.google[:private_key],
      client_email: Rails.application.credentials.google[:client_email],
      client_id: Rails.application.credentials.google[:client_id],
      auth_uri: "https://accounts.google.com/o/oauth2/auth",
      token_uri: "https://oauth2.googleapis.com/token",
      auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
      client_x509_cert_url: Rails.application.credentials.google[:client_x509_cert_url],
    }.to_json
  end

NoMethodError (undefined method ``read' for "{\"type\":\"service_acco...

The key thing I was missing (as pointed out by miggitymac in this answer ) is that the client is expecting an IO object (a file), not a string.我缺少的关键(正如miggitymac此答案中指出的那样)是客户端期望 IO object (文件),而不是字符串。

With the addition of StringIO.new , this now works as expected:添加StringIO.new ,现在可以按预期工作:

def call
  auth = Google::Auth::ServiceAccountCredentials.make_creds(
    json_key_io: StringIO.new(credentials),
    scope: Google::Apis::ClassroomV1::AUTH_CLASSROOM_ROSTERS
  )
end

private

  def credentials
    @credentials ||= {
      type: "service_account",
      project_id: Rails.application.credentials.google[:project_id],
      private_key_id: Rails.application.credentials.google[:private_key_id],
      private_key: Rails.application.credentials.google[:private_key],
      client_email: Rails.application.credentials.google[:client_email],
      client_id: Rails.application.credentials.google[:client_id],
      auth_uri: "https://accounts.google.com/o/oauth2/auth",
      token_uri: "https://oauth2.googleapis.com/token",
      auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
      client_x509_cert_url: Rails.application.credentials.google[:client_x509_cert_url],
    }.to_json
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM