Skip to content

Instantly share code, notes, and snippets.

@skyriser
Created January 17, 2020 04:29
Show Gist options
  • Save skyriser/dc8950f3f118d802d3fc90d36a8d91af to your computer and use it in GitHub Desktop.
Save skyriser/dc8950f3f118d802d3fc90d36a8d91af to your computer and use it in GitHub Desktop.
JWT使ってトークン取ってREST APIにリクエストしたりするやつ
require 'jwt'
class GoogleApiJwtTestService
def call
claims = {
iss: 'XXXX.iam.gserviceaccount.com',
scope: 'https://www.googleapis.com/auth/XXXX',
aud: 'https://www.googleapis.com/oauth2/v4/token',
exp: (Time.zone.now + 3.minutes).to_i,
iat: Time.zone.now.to_i
}
token = JWT.encode(claims, rsa_private, 'RS256')
body = {
assertion: token,
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer'
}
response = RestClient.post(
'https://www.googleapis.com/oauth2/v4/token',
body
)
access_token = JSON.parse(response.body)['access_token']
result = RestClient.get(
'https://XXXXX...',
{ Authorization: "Bearer #{access_token}" }
)
ap result
end
private
def rsa_private_key
"-----BEGIN PRIVATE KEY-----\n...."
end
def rsa_private
OpenSSL::PKey::RSA.new(rsa_private_key)
end
def rsa_public
rsa_private.public_key
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment