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.
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.
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