Get FCM Service Account Access Token in Ruby

by mmyoji

2 min read

When you want to send a push notification through Firebase Cloud Messaging (FCM), you have to get access token for it.

As this page says, you need a service account JSON file from your Firebase project and can get the access token with this JSON file and Google's Ruby SDK.

However, Google's Ruby SDKs are always confusing and not well-documented.

If you have a trouble to use it, this post will help you.

Get Access Token with Ruby SDK

Suppose you already have the Service Account JSON file.

If you already use google-api-client gem, you don't need to install extra dependencies to your project.

If you don't, use googleauth gem for the porpose. ( google-api-client depends on the googleauth )

For the Service Account, use the following code like says:

I refers googleauth v0.7.1 here.

require "googleauth"

# scope for FCM
scope = ""

authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  scope: scope,


# You can access the token with this method.
# You can know the expiration time with this method.

And if you want to cache the token, you can use 2 Stores classes.

  • Google::Auth::Stores::FileTokenStore
  • Google::Auth::Stores::RedisTokenStore

You will use the latter Redis store in most cases because the File one isn't thread-safe (if this code is, true), it's thread-safe.),

The usage is like that:

require "googleauth"
require "googleauth/stores/redis_token_store"

ACCESS_TOKEN = "access_token"
EXPIRES_AT   = "expires_at"

# this is from
redis = "redis://:p4ssw0rd@")
store = redis)

authorizer = Google::Auth::ServiceAccountCredentials.make_creds(options)

if store.load(ACCESS_TOKEN) && store.load(EXPIRES_AT)
   authorizer.access_token = store.load(ACCESS_TOKEN)
   # this `#expires_at=` method convert Integer to Time.
   authorizer.expires_at   = store.load(EXPIRES_AT)

# this `#expired?` method will returns false if `#expires_at` is not set. confusing.
if authorizer.access_token.nil? || (authorizer.expires_at && authorizer.expired?)
  authorizer.fetch_access_token!, authorizer.access_token), authorizer.expires_at.to_i)

# you can almost always valid access token.

Or your app process lives for a long time, you just use singleton class for it.