使用google-auth-library-ruby 0.9+编码JWT

时间:2017-07-28 18:14:13

标签: ruby google-compute-engine

我目前正在尝试为S2AP设置向Google发送对象。 Google建议签署this之类的JWT:

jwt = {
   "iss"=> SERVICE_ACCOUNT_EMAIL_ADDRESS,
   "aud" => "google",
   "typ" => "savetoandroidpay",
   "iat"=> Time.now.utc.to_i,
   "payload" => {
     "loyaltyObjects" => [], #Loyalty objects
     "offerObjects" => [], #Offer objects
     "loyaltyClasses" => [], #Loyalty classes
     "offerClasses" => [] #Offer classes
   },
   "origins"=> ['http://baconrista.com', 'https://baconrista.com']
}
private_key = Google::APIClient::PKCS12.load_key(SERVICE_ACCOUNT_PRIVATE_KEY, 'notasecret')
jwtEncoded = JWT.encode(jwt, private_key, "RS256")

但是,由于0.8不再是标准,并且不再支持Google::APIClient,我无法找到如何使用Compute引擎服务帐户提供的JSON文件对JWT进行签名。< / p>

我目前已经设置了所有其他内容,以生成访问令牌以使用带有OAuth2身份验证的googles API进行通话,但在我的生活中无法弄清楚如何对这些JWT进行编码。

作为参考,您可以通过ruby gem

从Google获取访问令牌
compute = Google::Apis::ComputeV1::ComputeService.new
File.open(CONFIG[:GOOGLE_APPLICATION_CREDENTIALS], "r") do |json_io|
  compute.authorization = Google::Auth::DefaultCredentials.make_creds(scope: 'https://www.googleapis.com/auth/wallet_object.issuer', json_key_io: json_io)
end
TOKEN = compute.authorization.fetch_access_token!

1 个答案:

答案 0 :(得分:0)

为了解决使用较新服务(未完全完成)签署jwt的能力不足的问题,我最终将private_key从他们拥有的json密钥文件中拉出来,然后签名如下:

def create_signed_JWT(obj, type)
  JSON.parse(File.open(keyfile.path, 'rb').read)
  jwt = {
    iss: credentials['client_email'],
    aud: "google",
    typ: "savetoandroidpay",
    iat: Time.now.utc.to_i,
    payload: {
      "#{type}Objects": obj
    },
    origins: [ "https://#{CONFIG[:domain]}", "http://#{CONFIG[:domain]}" ]
  }
  JWT.encode(jwt, OpenSSL::PKey::RSA.new(credentials['private_key'], nil), "RS256")
end

obj是json格式的offer / loyalty对象, type是对象的类型