[RUBY] Sign in with Apple using gem's apple_id in Rails and cache Apple's JWK

If you want to sign in with Apple in your Rails app, you need to validate your id_token in Rails because Sign in with Apple is OpenID Connect after all. If it is Ruby, the verification can be done easily by using this gem https://github.com/nov/apple_id.

Verify id_token using apple_id

id_token = AppleID::IdToken.decode(id_token)
id_token.verify!(code: code)

You can verify id_token like this, but what is done in the verify! Method is to get the public key (JWK) provided by Apple by HTTPS and use that JWK to verify the signature. doing. By default, it communicates with Apple via HTTPS every time it is verified, but since this public key is rarely updated, it can be cached, and it is desirable to cache it as a server implementation as well.

1.0.0 of gem's apple_id was recently released, and with this version upgrade, JWK can be cached anywhere. In this article, I will show you how to cache it.

Caching method

The cache method is very simple, just set the class that implements the fetch method that takes only one argument in AppleID :: JWKS.cache. You can get JWK by calling yield in the fetch method. For example, if you want to cache it in a process, write the following code.

class ProcessCache
  def initialize
    @cache = {}
  end

  def fetch(cache_key)
    @cache[cache_key] ||= yield
  end
end

AppleID::JWKS.cache = ProcessCache.new

AppleID :: JWKS.cache is defined as a class variable, so as an implementation of the Cache class, if you assign it to an instance variable, it will be cached in the process. Even if you want to save it in a file, cache server, DB, etc. instead of a process, you can replace it by implementing the fetch method in the same way, which is convenient. The Cache class should be implemented under app or lib, prepare config / initializers / apple_id.rb, etc., and assign to AppleID :: JWKS.cache there.

Recommended Posts

Sign in with Apple using gem's apple_id in Rails and cache Apple's JWK
Japaneseize using i18n with Rails
[Apple login] Sign in with Apple implementation procedure (Ruby on Rails)
Succeeded in loading js manually compiled using webpack with rails6
Implement login function simply with name and password in Rails (3)
Things to keep in mind when using Sidekiq with Rails
Try using view_component with rails
[Ruby on Rails] How to log in with only your name and password using the gem devise